Prime numbers after prime P with sum S | Java Program to print all N primes after prime P whose sum equals S ; vector to store prime and N primes whose sum equals given S ; function to check prime number ; square root of x ; since 1 is not prime number ; if any factor is found return false ; no factor found ; function to display N primes whose sum equals S ; function to evaluate all possible N primes whose sum equals S ; if total equals S And total is reached using N primes ; display the N primes ; if total is greater than S or if index has reached last element or if set size reached to maximum or greater than maximum ; add prime . get ( index ) to set vector ; include the ( index ) th prime to total ; remove element from set vector ; exclude ( index ) th prime ; function to generate all primes ; all primes less than S itself ; if i is prime add it to prime vector ; if primes are less than N ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static ArrayList < Integer > set = new ArrayList < Integer > ( ) ; static ArrayList < Integer > prime = new ArrayList < Integer > ( ) ; static boolean isPrime ( int x ) { int sqroot = ( int ) Math . sqrt ( x ) ; if ( x == 1 ) return false ; for ( int i = 2 ; i <= sqroot ; i ++ ) if ( x % i == 0 ) return false ; return true ; } static void display ( ) { int length = set . size ( ) ; for ( int i = 0 ; i < length ; i ++ ) System . out . print ( set . get ( i ) + " ▁ " ) ; System . out . println ( ) ; } static void primeSum ( int total , int N , int S , int index ) { if ( total == S && set . size ( ) == N ) { display ( ) ; return ; } if ( total > S || index == prime . size ( ) || set . size ( ) >= N ) return ; set . add ( prime . get ( index ) ) ; primeSum ( total + prime . get ( index ) , N , S , index + 1 ) ; set . remove ( set . size ( ) - 1 ) ; primeSum ( total , N , S , index + 1 ) ; } static void allPrime ( int N , int S , int P ) { for ( int i = P + 1 ; i <= S ; i ++ ) { if ( isPrime ( i ) ) prime . add ( i ) ; } if ( prime . size ( ) < N ) return ; primeSum ( 0 , N , S , 0 ) ; } public static void main ( String args [ ] ) { int S = 54 , N = 2 , P = 3 ; allPrime ( N , S , P ) ; } }