Represent n as the sum of exactly k powers of two | Set 2 | Function to print k numbers which are powers of two and whose sum is equal to n ; Initialising the sum with k ; Initialising an array A with k elements and filling all elements with 1 ; Iterating A [ ] from k - 1 to 0 ; Update sum and A [ i ] till sum + A [ i ] is less than equal to n ; Impossible to find the combination ; Possible solution is stored in A [ ] ; Driver Code
function FindAllElements ( n , k ) { let sum = k ; let A = new Array ( k ) . fill ( 1 ) ; for ( let i = k - 1 ; i >= 0 ; -- i ) { while ( sum + A [ i ] <= n ) { sum += A [ i ] ; A [ i ] *= 2 ; } } if ( sum != n ) { document . write ( " " ) ; } else { for ( let i = 0 ; i < k ; ++ i ) document . write ( A [ i ] + " " ) ; } } let n = 12 ; let k = 6 ; FindAllElements ( n , k ) ;