Represent N as sum of K even or K odd numbers with repetitions allowed | C ++ implementation to find an array of size K with all the even or odd elements in the array ; 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 ; Printing the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getArrayOfSizeK ( int n , int k ) { vector < int > ans ; int odd = n - ( ( k - 1 ) * 1 ) ; if ( odd > 0 && odd % 2 != 0 ) { for ( int i = 0 ; i < k - 1 ; i ++ ) { ans . push_back ( 1 ) ; } ans . push_back ( odd ) ; } int even = n - ( ( k - 1 ) * 2 ) ; if ( even > 0 && even % 2 == 0 && ans . size ( ) == 0 ) { for ( int i = 0 ; i < k - 1 ; i ++ ) { ans . push_back ( 2 ) ; } ans . push_back ( even ) ; } if ( ans . size ( ) > 0 ) { for ( int i = 0 ; i < k ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } else { cout << " NO " << endl ; } } int main ( ) { int n = 10 , k = 3 ; getArrayOfSizeK ( n , k ) ; return 0 ; }