Represent n as the sum of exactly k powers of two | Set 2

Given two integers n and k, the task is to find whether it is possible to represent n as the sum of exactly k powers of 2. If possible then print k positive integers such that they are powers of 2 and their sum is exactly equal to n else print Impossible.

Examples:

Input: n = 9, k = 4
Output: 1 2 2 4
1, 2 and 4 are all powers of 2 and 1 + 2 + 2 + 4 = 9.



Input: n = 3, k = 7
Output: Impossible
It is impossible since 3 cannot be represented as sum of 7 numbers which are powers of 2.

We have discussed one approach to solve this problem in Find k numbers which are powers of 2 and have sum N. In this post, a different approach is being discussed.

Approach:

  • Create an array arr[] of size k with all elements initialized to 1 and create a variable sum = k.
  • Now starting from the last element of arr[]
    • If sum + arr[i] ≤ n then update sum = sum + arr[i] and arr[i] = arr[i] * 2.
    • Else skip the current element.
  • If sum = n then the contents of arr[] are the required elements.
  • Else it is impossible to represent n as exactly k powers of 2.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above approach
#include <iostream>
using namespace std;
  
// Function to print k numbers which are powers of two
// and whose sum is equal to n
void FindAllElements(int n, int k)
{
    // Initialising the sum with k
    int sum = k;
  
    // Initialising an array A with k elements
    // and filling all elements with 1
    int A[k];
    fill(A, A + k, 1);
  
    for (int i = k - 1; i >= 0; --i) {
  
        // Iterating A[] from k-1 to 0
        while (sum + A[i] <= n) {
  
            // Update sum and A[i]
            // till sum + A[i] is less than equal to n
            sum += A[i];
            A[i] *= 2;
        }
    }
  
    // Impossible to find the combination
    if (sum != n) {
        cout << "Impossible";
    }
  
    // Possible solution is stored in A[]
    else {
        for (int i = 0; i < k; ++i)
            cout << A[i] << ' ';
    }
}
  
// Driver code
int main()
{
    int n = 12;
    int k = 6;
  
    FindAllElements(n, k);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the above approach 
import java.util.Arrays;
  
public class GfG {
      
    // Function to print k numbers which are powers of two 
    // and whose sum is equal to n 
    public static void FindAllElements(int n, int k) 
    
        // Initialising the sum with k 
        int sum = k; 
        
        // Initialising an array A with k elements 
        // and filling all elements with 1 
        int[] A = new int[k]; 
        Arrays.fill(A, 0, k, 1); 
          
        for (int i = k - 1; i >= 0; --i) { 
        
            // Iterating A[] from k-1 to 0 
            while (sum + A[i] <= n) { 
        
                // Update sum and A[i] 
                // till sum + A[i] is less than equal to n 
                sum += A[i]; 
                A[i] *= 2
            
        
        
        // Impossible to find the combination 
        if (sum != n) { 
            System.out.print("Impossible"); 
        
        
        // Possible solution is stored in A[] 
        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); 
    }
}
    
// This code is contributed by Rituraj Jain

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the above approach
  
# Function to print k numbers which are 
# powers of two and whose sum is equal to n
def FindAllElements(n, k):
      
    # Initialising the sum with k
    sum = k
  
    # Initialising an array A with k elements
    # and filling all elements with 1
    A = [1 for i in range(k)]
    i = k - 1
    while(i >= 0):
          
        # Iterating A[] from k-1 to 0
        while (sum + A[i] <= n):
              
            # Update sum and A[i] till
            # sum + A[i] is less than equal to n
            sum += A[i]
            A[i] *= 2
        i -= 1
      
    # Impossible to find the combination
    if (sum != n):
        print("Impossible")
  
    # Possible solution is stored in A[]
    else:
        for i in range(0, k, 1):
            print(A[i], end = ' ')
  
# Driver code
if __name__ == '__main__':
    n = 12
    k = 6
  
    FindAllElements(n, k)
  
# This code is contributed by
# Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach 
using System;
  
class GfG 
{
      
    // Function to print k numbers
    // which are powers of two 
    // and whose sum is equal to n 
    public static void FindAllElements(int n, int k) 
    
        // Initialising the sum with k 
        int sum = k; 
          
        // Initialising an array A with k elements 
        // and filling all elements with 1 
        int[] A = new int[k]; 
        for(int i = 0; i < k; i++)
            A[i] = 1;
          
        for (int i = k - 1; i >= 0; --i) 
        
          
            // Iterating A[] from k-1 to 0 
            while (sum + A[i] <= n) 
            
          
                // Update sum and A[i] 
                // till sum + A[i] is less than equal to n 
                sum += A[i]; 
                A[i] *= 2; 
            
        
          
        // Impossible to find the combination 
        if (sum != n)
        
            Console.Write("Impossible"); 
        
          
        // Possible solution is stored in A[] 
        else
        
            for (int i = 0; i < k; ++i) 
                Console.Write(A[i] + " "); 
        
    
      
    // Driver code
    public static void Main(String []args)
    {
          
        int n = 12; 
        int k = 6; 
          
        FindAllElements(n, k); 
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation of the above approach 
  
// Function to print k numbers which are 
// powers of two and whose sum is equal to n 
function FindAllElements($n, $k
    // Initialising the sum with k 
    $sum = $k
  
    // Initialising an array A with k elements 
    // and filling all elements with 1 
    $A = array_fill(0, $k, 1) ;
  
  
    for ($i = $k - 1; $i >= 0; --$i)
    
  
        // Iterating A[] from k-1 to 0 
        while ($sum + $A[$i] <= $n
        
  
            // Update sum and A[i] till  
            // sum + A[i] is less than equal to n 
            $sum += $A[$i]; 
            $A[$i] *= 2; 
        
    
  
    // Impossible to find the combination 
    if ($sum != $n
    
        echo"Impossible"
    
  
    // Possible solution is stored in A[] 
    else
    
        for ($i = 0; $i < $k; ++$i
            echo $A[$i], ' '
    
  
// Driver code 
$n = 12; 
$k = 6; 
  
FindAllElements($n, $k); 
  
// This code is contributed by Ryuga
?>

chevron_right


Output:

1 1 1 1 4 4


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.