# Find k numbers which are powers of 2 and have sum N in C++

C++Server Side ProgrammingProgramming

Suppose we have two numbers N and K. The task is to print K numbers, which are the power of 2 and their sum is N. If it is not possible, then return -1. Suppose N = 9 and K = 4, then the output will be 4 2 2 1, whose sum is 9, and a number of elements is 4, and each of them is a power of 2.

We have to follow these steps to solve this problem −

• If k is less than the number of set bits in N or more than the number N, then return -1

• Add the powers of two at set bits into the Priority queue

• Initiate the priority queue till we get K elements, then remove the element from the priority queue

• Insert the removed element/2 twice into the priority queue again

• If k elements are achieved, then print them.

## Example

Live Demo

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
void displayKnumbers(int n, int k) {
int set_bit_count = __builtin_popcount(n);
if (k < set_bit_count || k > n) {
cout << "-1";
return;
}
priority_queue<int> queue;
int two = 1;
while (n) {
if (n & 1) {
queue.push(two);
}
two = two * 2;
n = n >> 1;
}
while (queue.size() < k) {
int element = queue.top();
queue.pop();
queue.push(element / 2);
queue.push(element / 2);
}
int ind = 0;
while (ind < k) {
cout << queue.top() << " ";
queue.pop();
ind++;
}
}
int main() {
int n = 30, k = 5;
cout << "Numbers are: ";
displayKnumbers(n, k);
}

## Output

Numbers are: 8 8 8 4 2