Represent N as sum of K even or K odd numbers with repetitions allowed | Function to find the array with all the even / odd elements ; First let 's check  kth is odd or even ; If last element is also an odd number then we can choose odd elements for our answer ; Add 1 in the array ( k - 1 ) times ; Add last odd element ; If array of even elements would be the answer then k - 1 elements would be 2 ; If last element is also an even number then we can choose even elements for our answer ; Add 2 in the array ( k - 1 ) times ; Add last even element ; Prleting the array ; Driver Code
function getArrayOfSizeK ( n , k ) { let ans = [ ] ; let odd = n - ( ( k - 1 ) * 1 ) ; if ( odd > 0 && odd % 2 != 0 ) { for ( let i = 0 ; i < k - 1 ; i ++ ) { ans . push ( 1 ) ; } ans . push ( odd ) ; } let even = n - ( ( k - 1 ) * 2 ) ; if ( even > 0 && even % 2 == 0 && ans . length == 0 ) { for ( let i = 0 ; i < k - 1 ; i ++ ) { ans . push ( 2 ) ; } ans . push ( even ) ; } if ( ans . length > 0 ) { for ( let i = 0 ; i < k ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } else { document . write ( " " ) ; } } let n = 10 , k = 3 ; getArrayOfSizeK ( n , k ) ;