
- 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 = 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
- 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++
- Count ways to express a number as sum of powers in C++
- Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n in C++
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 in C++
- 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++
- Powers of two and subsequences in C++
- Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + .. + n in C++
- Program to check whether number is a sum of powers of three in Python
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n – 1)^2
- Sum of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n) in C++
- C++ Representation of a Number in Powers of Other
- Minimum number of operations required to sum to binary string S using C++.
- Sum of the digits of a number N written in all bases from 2 to N/2 in C++
Advertisements