# Powers of 2 to required sum in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 = 24 + 20 = 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

Live Demo

#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
Updated on 17-Apr-2020 06:43:33