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.
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 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
- Once K elements are achieved, print them.
element/2 twice into the Priority Queue again.
Below is the implementation of the above approach:
4 2 2 1
- Find the sum of numbers from 1 to n excluding those which are powers of K
- Sum of first N natural numbers which are not powers of K
- Sum of fifth powers of the first n natural numbers
- Print all integers that are sum of powers of two given numbers
- Sum of fourth powers of first n odd natural numbers
- Sum of fourth powers of the first n natural numbers
- Sum of first N natural numbers by taking powers of 2 as negative number
- Count numbers in a range having GCD of powers of prime factors equal to 1
- Represent n as the sum of exactly k powers of two | Set 2
- Powers of 2 to required sum
- Representation of a number in powers of other
- Check if a number can be represented as sum of non zero powers of 2
- Print all prime factors and their powers
- Balance pans using given weights that are powers of a number
- Number of triangles possible with given lengths of sticks which are powers of 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.