- 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

# Powers of 2 to required sum in C++

In this problem, we are given an integer N. Our task is to print the number which when raised to the power of 2 gives the number.

Let’s take an example to understand the problem

**Input** − 17

**Output** − 0, 4

**Explanation** − 17 = 2^{4} + 2^{0} = 16 + 1

To solve this problem, we will divide the number with 2 recursively. By this method, every number can be represented as a power of 2. This method is used to convert the number to its binary equivalent.

## Example

The program to show the implementation of our solution

#include <bits/stdc++.h> using namespace std; void sumPower(long int x) { vector<long int> powers; while (x > 0){ powers.push_back(x % 2); x = x / 2; } for (int i = 0; i < powers.size(); i++){ if (powers[i] == 1){ cout << i; if (i != powers.size() - 1) cout<<", "; } } cout<<endl; } int main() { int number = 23342; cout<<"Powers of 2 that sum upto "<<number<<"are : "; sumPower(number); return 0; }

## Output

Powers of 2 that sum upto 23342are : 1, 2, 3, 5, 8, 9, 11, 12, 14

- Related Questions & Answers
- Find k numbers which are powers of 2 and have sum N in C++
- Check if a number can be represented as sum of non zero powers of 2 in C++
- Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n in C++
- Count ways to express a number as sum of powers in C++
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 in C++
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n – 1)^2
- Program to check whether number is a sum of powers of three in Python
- 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++
- PHP program to find the sum of the 5th powers of first n natural numbers
- Find required sum pair with JavaScript
- Sum of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n) in C++
- Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + .. + n in C++
- Column sum of elements of 2-D arrays in JavaScript
- Powers of two and subsequences in C++

Advertisements