Find three prime numbers with given sum | Python3 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
from math import sqrt NEW_LINE MAX = 100001 ; NEW_LINE primes = [ ] ; NEW_LINE def initialize ( ) : NEW_LINE INDENT numbers = [ 0 ] * ( MAX + 1 ) ; NEW_LINE n = MAX ; NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( not numbers [ i ] ) : NEW_LINE INDENT for j in range ( i * i , n + 1 , i ) : NEW_LINE INDENT numbers [ j ] = True ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( numbers [ i ] == False ) : NEW_LINE INDENT primes . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def findNums ( num ) : NEW_LINE INDENT ans = False ; NEW_LINE first = - 1 ; NEW_LINE second = - 1 ; NEW_LINE third = - 1 ; NEW_LINE for i in range ( num ) : NEW_LINE INDENT first = primes [ i ] ; NEW_LINE for j in range ( num ) : NEW_LINE INDENT second = primes [ j ] ; NEW_LINE third = num - first - second ; NEW_LINE if ( third in primes ) : NEW_LINE INDENT ans = True ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT print ( first , second , third ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 101 ; NEW_LINE initialize ( ) ; NEW_LINE findNums ( n ) ; NEW_LINE DEDENT