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
using System ; using System . Collections . Generic ; class GFG { static int MAX = 100001 ; static List < int > primes = new List < int > ( ) ; static void initialize ( ) { bool [ ] numbers = new bool [ MAX + 1 ] ; 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 . Add ( i ) ; } static 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 ( Array . BinarySearch ( primes . ToArray ( ) , third ) >= 0 ) { ans = true ; break ; } } if ( ans ) break ; } if ( ans ) Console . WriteLine ( first + " ▁ " + second + " ▁ " + third ) ; else Console . WriteLine ( - 1 ) ; } static void Main ( ) { int n = 101 ; initialize ( ) ; findNums ( n ) ; } }