
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 = 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
#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
Advertisements