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
< ? php function FindAllElements ( $ n , $ k ) { $ sum = $ k ; $ A = array_fill ( 0 , $ k , 1 ) ; for ( $ i = $ k - 1 ; $ i >= 0 ; -- $ i ) { while ( $ sum + $ A [ $ i ] <= $ n ) { $ sum += $ A [ $ i ] ; $ A [ $ i ] *= 2 ; } } if ( $ sum != $ n ) { echo " Impossible " ; } else { for ( $ i = 0 ; $ i < $ k ; ++ $ i ) echo $ A [ $ i ] , ' ▁ ' ; } } $ n = 12 ; $ k = 6 ; FindAllElements ( $ n , $ k ) ; ? >