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 = 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

553 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements