Find k numbers which are powers of 2 and have sum N | Set 1

Given two numbers N and K. The task is to print K numbers which are powers of 2 and their sum is N. Print -1 if not possible.

Examples:

Input: N = 9, K = 4
Output: 4 2 2 1
4 + 2 + 2 + 1 = 9 

Input: N = 4, K = 5
Output: -1 


Approach: The below algorithm can be followed to solve the above problem:

  • If the K is less than the number of set bits in N or more than the number of set bits in N, then it is not possible.
  • Insert the powers of two at set bits into Priority Queue.
  • Iterate in the Priority Queue till we get K elements, pop() the topmost element and
  • push()
  • element/2 twice into the Priority Queue again.

  • Once K elements are achieved, print them.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find k numbers that 
// are power of 2 and have sum equal 
// to N
#include <bits/stdc++.h>
using namespace std;
  
// function to print numbers
void printNum(int n, int k)
{
    // Count the number of set bits
    int x = __builtin_popcount(n);
  
    // Not-possible conditon
    if (k < x || k > n) {
        cout << "-1";
        return;
    }
  
    // Stores the number
    priority_queue<int> pq;
  
    // Get the set bits
    int two = 1;
    while (n) {
        if (n & 1) {
            pq.push(two);
        }
  
        two = two * 2;
        n = n >> 1;
    }
  
    // Iterate till we get K elements
    while (pq.size() < k) {
  
        // Get the topmost element
        int el = pq.top();
        pq.pop();
  
        // Push the elements/2 into 
        // priority queue
        pq.push(el / 2);
        pq.push(el / 2);
    }
  
    // Print all elements
    int ind = 0;
    while (ind < k) {
        cout << pq.top() << " ";
        pq.pop();
        ind++;
    }
}
  
// Driver Code
int main()
{
    int n = 9, k = 4;
    printNum(n, k);
    return 0;
}

chevron_right


Output:

4 2 2 1

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



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

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.