Split N as the sum of K numbers satisfying the given conditions | Java Program to implement the above approach ; Vector 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
import java . util . * ; class GFG { static Vector < Integer > primes = new Vector < > ( ) ; static void SieveOfEratosthenes ( ) { boolean [ ] prime = new boolean [ 10005 ] ; Arrays . fill ( prime , 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 ) { Vector < Integer > prod = new Vector < > ( ) ; SieveOfEratosthenes ( ) ; int l = primes . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i + 1 ; j < l ; j ++ ) { if ( primes . get ( i ) * primes . get ( j ) > 0 ) prod . add ( primes . get ( i ) * primes . get ( j ) ) ; } } Collections . sort ( prod ) ; int sum = 0 ; for ( int i = 0 ; i < k - 1 ; i ++ ) sum += prod . get ( i ) ; if ( sum > n ) System . out . print ( " - 1" ) ; else { for ( int i = 0 ; i < k - 1 ; i ++ ) { System . out . print ( prod . get ( i ) + " , ▁ " ) ; } System . out . print ( n - sum + "NEW_LINE"); } } public static void main ( String [ ] args ) { int n = 52 , k = 5 ; generate ( n , k ) ; } }