Represent n as the sum of exactly k powers of two | Set 2 | Java implementation of the above approach ; 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
import java . util . Arrays ; public class GfG { public static void FindAllElements ( int n , int k ) { int sum = k ; int [ ] A = new int [ k ] ; Arrays . fill ( A , 0 , k , 1 ) ; for ( int i = k - 1 ; i >= 0 ; -- i ) { while ( sum + A [ i ] <= n ) { sum += A [ i ] ; A [ i ] *= 2 ; } } if ( sum != n ) { System . out . print ( " Impossible " ) ; } else { for ( int i = 0 ; i < k ; ++ i ) System . out . print ( A [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 12 ; int k = 6 ; FindAllElements ( n , k ) ; } }