Check if a number can be written as a sum of ' k ' prime numbers | Checking if a number is prime or not ; check for numbers from 2 to sqrt ( x ) if it is divisible return false ; Returns true if N can be written as sum of K primes ; N < 2 K directly return false ; If K = 1 return value depends on primality of N ; if N is even directly return true ; ; If N is odd , then one prime must be 2. All other primes are odd and cannot have a pair sum as even . ; If K >= 3 return true ; ; Driver code
function isprime ( x ) { for ( i = 2 ; i * i <= x ; i ++ ) if ( x % i == 0 ) return false ; return true ; } function isSumOfKprimes ( N , K ) { if ( N < 2 * K ) return false ; if ( K == 1 ) return isprime ( N ) ; if ( K == 2 ) { if ( N % 2 == 0 ) return true ; return isprime ( N - 2 ) ; } return true ; } var n = 10 , k = 2 ; if ( isSumOfKprimes ( n , k ) ) document . write ( " " ) ; else document . write ( " " ) ;