Split N as the sum of K numbers satisfying the given conditions | C # program to implement the above approach ; List to store prime numbers ; Function to generate prime numbers using SieveOfEratosthenes ; Boolean 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
using System ; using System . Collections . Generic ; class GFG { static List < int > primes = new List < int > ( ) ; static void SieveOfEratosthenes ( ) { bool [ ] prime = new bool [ 10005 ] ; for ( int i = 0 ; i < 10005 ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= 1000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= 1000 ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= 1000 ; p ++ ) if ( prime [ p ] ) primes . Add ( p ) ; } static void generate ( int n , int k ) { List < int > prod = new List < int > ( ) ; SieveOfEratosthenes ( ) ; int l = primes . Count ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i + 1 ; j < l ; j ++ ) { if ( primes [ i ] * primes [ j ] > 0 ) prod . Add ( primes [ i ] * primes [ j ] ) ; } } prod . Sort ( ) ; int sum = 0 ; for ( int i = 0 ; i < k - 1 ; i ++ ) sum += prod [ i ] ; if ( sum > n ) Console . Write ( " - 1" ) ; else { for ( int i = 0 ; i < k - 1 ; i ++ ) { Console . Write ( prod [ i ] + " , ▁ " ) ; } Console . Write ( n - sum + " STRNEWLINE " ) ; } } public static void Main ( String [ ] args ) { int n = 52 , k = 5 ; generate ( n , k ) ; } }