Split N as the sum of K numbers satisfying the given conditions | Array to store prime numbers ; Function to generate prime numbers using SieveOfEratosthenes ; array to store primes ; If p is a prime ; Mark all its multiples as non - prime ; Print all prime numbers ; Function to generate n as the sum of k numbers where atleast K - 1 are distinct and are product of 2 primes ; Stores the product of every pair of prime number ; Sort the products ; If sum exceeds n ; Otherwise , print the k required numbers ; Driver Code
let primes = new Array ( ) ; function SieveOfEratosthenes ( ) { let prime = new Array ( 10005 ) ; prime . fill ( true ) ; for ( let p = 2 ; p * p <= 1000 ; p ++ ) { if ( prime [ p ] == true ) { for ( let i = p * p ; i <= 1000 ; i += p ) prime [ i ] = false ; } } for ( let p = 2 ; p <= 1000 ; p ++ ) if ( prime [ p ] ) primes . push ( p ) ; } function generate ( n , k ) { let prod = new Array ( ) ; SieveOfEratosthenes ( ) ; let l = primes . length ; for ( let i = 0 ; i < l ; i ++ ) { for ( let j = i + 1 ; j < l ; j ++ ) { if ( primes [ i ] * primes [ j ] > 0 ) prod . push ( primes [ i ] * primes [ j ] ) ; } } prod . sort ( ( a , b ) => a - b ) let sum = 0 ; for ( let i = 0 ; i < k - 1 ; i ++ ) sum += prod [ i ] ; if ( sum > n ) document . write ( " " ) ; else { for ( let i = 0 ; i < k - 1 ; i ++ ) { document . write ( prod [ i ] + " " ) ; } document . write ( n - sum + " " ) ; } } let n = 52 , k = 5 ; generate ( n , k ) ;