- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

#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

- Related Questions & Answers
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n in C++
- PHP program to find the sum of the first n natural numbers who are not powers of a specific number ‘k’
- Powers of 2 to required sum in C++
- PHP program to find the sum of the 5th powers of first n natural numbers
- Count the numbers < N which have equal number of divisors as K in C++
- Python Program to Get K initial powers of N
- Find sum of Series with n-th term as n^2 - (n-1)^2 in C++
- Minimize the sum of squares of sum of N/2 paired formed by N numbers in C++
- Sum of first N natural numbers which are divisible by X or Y
- Find Sum of Series 1^2 - 2^2 + 3^2 - 4^2 ... upto n terms in C++
- Print all integers that are sum of powers of two given numbers in C++
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Java Program to Find sum of Series with n-th term as n^2 – (n-1)^2
- Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n in C++

Advertisements