Prime numbers after prime P with sum S | CPP 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 ; add prime [ 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
#include <iostream> NEW_LINE #include <vector> NEW_LINE #include <cmath> NEW_LINE using namespace std ; vector < int > set ; vector < int > prime ; bool isPrime ( int x ) { int sqroot = sqrt ( x ) ; bool flag = true ; if ( x == 1 ) return false ; for ( int i = 2 ; i <= sqroot ; i ++ ) if ( x % i == 0 ) return false ; return true ; } void display ( ) { int length = set . size ( ) ; for ( int i = 0 ; i < length ; i ++ ) cout << set [ i ] << " ▁ " ; cout << " STRNEWLINE " ; } void primeSum ( int total , int N , int S , int index ) { if ( total == S && set . size ( ) == N ) { display ( ) ; return ; } if ( total > S || index == prime . size ( ) ) return ; set . push_back ( prime [ index ] ) ; primeSum ( total + prime [ index ] , N , S , index + 1 ) ; set . pop_back ( ) ; primeSum ( total , N , S , index + 1 ) ; } void allPrime ( int N , int S , int P ) { for ( int i = P + 1 ; i <= S ; i ++ ) { if ( isPrime ( i ) ) prime . push_back ( i ) ; } if ( prime . size ( ) < N ) return ; primeSum ( 0 , N , S , 0 ) ; } int main ( ) { int S = 54 , N = 2 , P = 3 ; allPrime ( N , S , P ) ; return 0 ; }