Find three prime numbers with given sum | Java 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
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int MAX = 100001 ; static ArrayList < Integer > primes ; static void initialize ( ) { boolean [ ] numbers = new boolean [ 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 ) { boolean ans = false ; int first = - 1 , second = - 1 , third = - 1 ; for ( int i = 0 ; i < num ; i ++ ) { first = primes . get ( i ) ; for ( int j = 0 ; j < num ; j ++ ) { second = primes . get ( j ) ; third = num - first - second ; if ( Collections . binarySearch ( primes , third ) >= 0 ) { ans = true ; break ; } } if ( ans ) break ; } if ( ans ) System . out . println ( first + " ▁ " + second + " ▁ " + third ) ; else System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { int n = 101 ; primes = new ArrayList < > ( ) ; initialize ( ) ; findNums ( n ) ; } }