Find three prime numbers with given sum | C ++ implementation of the approach ; The vector primes holds the prime numbers ; Function to generate prime numbers ; Initialize the array elements to 0 s ; Set the non - primes to true ; Fill the vector primes with prime numbers which are marked as false in the numbers array ; Function to print three prime numbers which sum up to the number N ; Take the first prime number ; Take the second prime number ; Subtract the two prime numbers from the N to obtain the third number ; If the third number is prime ; Print the three prime numbers if the solution exists ; Driver code ; Function for generating prime numbers using Sieve of Eratosthenes ; Function to print the three prime numbers whose sum is equal to N
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100001 ; vector < int > primes ; void initialize ( ) { bool numbers [ MAX ] = { } ; int n = MAX ; for ( int i = 2 ; i * i <= n ; i ++ ) if ( ! numbers [ i ] ) for ( int j = i * i ; j <= n ; j += i ) numbers [ j ] = true ; for ( int i = 2 ; i <= n ; i ++ ) if ( numbers [ i ] == false ) primes . push_back ( i ) ; } void findNums ( int num ) { bool ans = false ; int first = -1 , second = -1 , third = -1 ; for ( int i = 0 ; i < num ; i ++ ) { first = primes [ i ] ; for ( int j = 0 ; j < num ; j ++ ) { second = primes [ j ] ; third = num - first - second ; if ( binary_search ( primes . begin ( ) , primes . end ( ) , third ) ) { ans = true ; break ; } } if ( ans ) break ; } if ( ans ) cout << first << " ▁ " << second << " ▁ " << third << endl ; else cout << -1 << endl ; } int main ( ) { int n = 101 ; initialize ( ) ; findNums ( n ) ; return 0 ; }