Given two integers n and k, the task is to find whether it is possible to represent n as the sum of exactly k powers of 2. If possible then print k positive integers such that they are powers of 2 and their sum is exactly equal to n else print Impossible.
Input: n = 9, k = 4
Output: 1 2 2 4
1, 2 and 4 are all powers of 2 and 1 + 2 + 2 + 4 = 9.
Input: n = 3, k = 7
It is impossible since 3 cannot be represented as sum of 7 numbers which are powers of 2.
We have discussed one approach to solve this problem in Find k numbers which are powers of 2 and have sum N. In this post, a different approach is being discussed.
- Create an array arr of size k with all elements initialized to 1 and create a variable sum = k.
- Now starting from the last element of arr
- If sum + arr[i] ≤ n then update sum = sum + arr[i] and arr[i] = arr[i] * 2.
- Else skip the current element.
- If sum = n then the contents of arr are the required elements.
- Else it is impossible to represent n as exactly k powers of 2.
Below is the implementation of the above approach:
1 1 1 1 4 4
- Minimum number of given powers of 2 required to represent a number
- Powers of 2 to required sum
- Powers of two and subsequences
- Ways to represent a number as a sum of 1's and 2's
- Find k numbers which are powers of 2 and have sum N | Set 1
- Sum of first N natural numbers which are not powers of K
- Representation of a number in powers of other
- Sum of fifth powers of the first n natural numbers
- Represent a given set of points by the best possible straight line
- Represent the given number as the sum of two composite numbers
- Find the sum of numbers from 1 to n excluding those which are powers of K
- Check if a number can be represented as sum of non zero powers of 2
- Print all integers that are sum of powers of two given numbers
- Sum of fourth powers of the first n natural numbers
- Sum of fourth powers of first n odd natural numbers
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.