- Related Questions & Answers
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- Powers of 2 to required sum in C++
- Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n in C++
- Count the numbers < N which have equal number of divisors as K in C++
- PHP program to find the sum of the first n natural numbers who are not powers of a specific number ‘k’
- PHP program to find the sum of the 5th powers of first n natural numbers
- Print all integers that are sum of powers of two given numbers in C++
- Minimize the sum of squares of sum of N/2 paired formed by N numbers in C++
- Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n in C++
- Sum of first N natural numbers which are divisible by X or Y
- C/C++ Program to Find sum of Series with n-th term as n power of 2 - (n-1) power of 2
- Program to find sum of series 1*2*3 + 2*3*4+ 3*4*5 + . . . + n*(n+1)*(n+2) in C++
- Find four factors of N with maximum product and sum equal to N - Set-2 in C++
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 in C++

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

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.

#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); }

Numbers are: 8 8 8 4 2

Advertisements