Prime numbers after prime P with sum S | Python 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
import math NEW_LINE set = [ ] NEW_LINE prime = [ ] NEW_LINE def isPrime ( x ) : NEW_LINE INDENT sqroot = int ( math . sqrt ( x ) ) NEW_LINE flag = True NEW_LINE if ( x == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , sqroot + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def display ( ) : NEW_LINE INDENT global set , prime NEW_LINE length = len ( set ) NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT print ( set [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def primeSum ( total , N , S , index ) : NEW_LINE INDENT global set , prime NEW_LINE if ( total == S and len ( set ) == N ) : NEW_LINE INDENT display ( ) NEW_LINE return NEW_LINE DEDENT if ( total > S or index == len ( prime ) ) : NEW_LINE INDENT return NEW_LINE DEDENT set . append ( prime [ index ] ) NEW_LINE primeSum ( total + prime [ index ] , N , S , index + 1 ) NEW_LINE set . pop ( ) NEW_LINE primeSum ( total , N , S , index + 1 ) NEW_LINE DEDENT def allPrime ( N , S , P ) : NEW_LINE INDENT global set , prime NEW_LINE for i in range ( P + 1 , S + 1 ) : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT prime . append ( i ) NEW_LINE DEDENT DEDENT if ( len ( prime ) < N ) : NEW_LINE INDENT return NEW_LINE DEDENT primeSum ( 0 , N , S , 0 ) NEW_LINE DEDENT S = 54 NEW_LINE N = 2 NEW_LINE P = 3 NEW_LINE allPrime ( N , S , P ) NEW_LINE