Open In App

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

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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;
}


Java




// 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


Python3




# 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


C#




// 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


PHP




<?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
?>


Javascript




<script>
 
// Javascript 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
    let sum = k;
         
    // Initialising an array A with k elements
    // and filling all elements with 1
    let A = new Array(k).fill(1);
     
         
    for (let 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) {
        document.write("Impossible");
    }
         
    // Possible solution is stored in A[]
    else {
        for (let i = 0; i < k; ++i)
            document.write(A[i] + " ");
    }
}
     
 
// Driver Code
 
let n = 12;
let k = 6;
         
FindAllElements(n, k);
 
</script>


Output

1 1 1 1 4 4 

Complexity Analysis:

  • Time Complexity: O(k*log2(n-k))
  • Auxiliary Space: O(k), since k extra space has been taken.


Similar Reads

Represent Integer as sum of exactly X Powers of three. The powers can repeat
Given two integers N and X (1&lt;=N&lt;=X&lt;=1e9), the task is to find if it is possible to represent N as exactly X powers of 3. Examples: Input: N = 9, X = 5Output: Yes Explanation: 9 = 3^1 + 3^1 + 3^0 + 3^0 + 3^0 Input: N = 9, X = 4Output: No Approach: To solve the problem follow the below idea: The idea is to use the ternary (base-3) represent
4 min read
Represent N as the sum of exactly K powers of two | Set 3
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. Otherwise, print "Impossible". If multiple answers exist, print any. Examples: Input: N = 5, K = 2Output: 4 1Explan
7 min read
Count ways to represent N as sum of powers of 2
Given an integer N, the task is to count the number of ways to represent N as the sum of powers of 2. Examples: Input: N = 4Output: 4Explanation: All possible ways to obtains sum N using powers of 2 are {4, 2+2, 1+1+1+1, 2+1+1}. Input: N = 5Output: 4Explanation: All possible ways to obtains sum N using powers of 2 are {4 + 1, 2+2 + 1, 1+1+1+1 + 1,
10 min read
Minimum powers of P and Q to represent N
Given integer N and values P and Q, The task is to calculate the minimum number of powers of P and Q required to generate N. Note: The 0th power of the values is also considered. Examples: Input: N = 15, P = 2, Q = 3Output: 3Explanation: We can make 15 by using (8, 4, 3) or (9, 3, 3). Both take 3 numbers. Input: N = 19, P = 4, Q = 3Output: 2Explana
6 min read
Minimum number of given powers of 2 required to represent a number
Given an integer x and an array arr[] each element of which is a power of 2. The task is to find the minimum number of integer powers of 2 from the array which when added give x. If it is not possible to represent x with the given array elements then print -1.Examples: Input: arr[] = {2, 4, 8, 2, 4}, x = 14 Output: 3 14 can be written as 8 + 4 + 2I
20 min read
Represent K^N as the sum of exactly N numbers
Given two numbers N and K, the task is to represent KN as the sum of exactly N numbers. Print NA if no such numbers are possible.Examples: Input: N = 5, K = 2 Output: 2 2 4 8 16 Explanation: 2 + 2 + 4 + 8 + 16 = 32 = 25Input: N = 4, K = 3 Output: 3 6 18 54 Explanation: 3 + 6 + 18 + 54 = 81 = 34 Approach: In order to obtain numbers such that their s
4 min read
Add two integers of different base and represent sum in smaller base of the two
Given two integers X, Y in base B1 and B2 respectively, the task is to find the sum of integers X and Y and represent the result in min of ( B1 and B2 ). Example: Input: X = 123, Y = 234, B1 = 6, B2 = 8 Output: 543 Explanation: Integer in base 10: 51 and 156 Sum of Integers: 207 Minimum Base: 6 Sum of Integer in Base 6 = 543 Input: X = 16, Y = 24,
17 min read
Express 2^N in exactly N+1 powers of 2
Given a positive integer N, the task is to express 2^N in the sum of powers of 2 and in exactly N+1 terms. Print those N+1 terms. Example: Input: N = 4Output: 1 1 2 4 8Explanation: 2^4 = 2^0 + 2^0 + 2^1 + 2^2 + 2^3 = 1 + 1 + 2 + 4 + 8 Input: N = 5Output: 1 1 2 4 8 16 Approach: As we know: 2^0 + 2^1 +.... 2^(N-1) = 2^N -1 Therefore, adding 1 at the
3 min read
Represent the given number as the sum of two composite numbers
Given an integer N, the task is to represent N as the sum of two composite integers. There can be multiple ways possible, print any one of them. If it is not possible to represent the number as the sum of two composite numbers then print -1.Examples: Input: N = 13 Output: 4 9 4 + 9 = 13 and both 4 and 9 are composite.Input: N = 18 Output: 4 14 Appr
4 min read
Print all integers that are sum of powers of two given numbers
Given three non-negative integers x, y and bound, the task is to print all the powerful integer ? bound in sorted order. A powerful integer is of the form xi + yj for all i, j ? 0. Examples: Input: x = 3, y = 5, bound = 10 Output: 2 4 6 8 10 30 + 50 = 1 + 1 = 2 30 + 51 = 1 + 5 = 6 31 + 50 = 3 + 1 = 4 31 + 51 = 3 + 5 = 8 32 + 50 = 9 + 1 = 10 Input:
8 min read