# Check if a number can be represented as sum of non zero powers of 2 in C++

C++Server Side ProgrammingProgramming

Here we will see, if we can represent a number as sum of two non-zero powers of 2. So we will check the given number N can be represented as (2x + 2y) where x, y > 0. Suppose a number is 10, this can be represented as 23 + 21.

The approach is simple. There are two cases. If the number n is even, it can be represented as 2x. Where x > 0. Another case is that is N is odd, it can never be represented as sum of powers of 2. We cannot use power as 0, so we cannot get odd numbers. for all odd numbers LSb of its binary representation is 1

## Example

Live Demo

#include <iostream>
using namespace std;
bool isSumofTwosPower(int n) {
if((n & 1) == 0){
return true;
} else {
return false;
}
}
int main() {
int num = 86;
if(isSumofTwosPower(num)){
cout << "Can be represented";
} else {
cout << "Cannot be represented";
}
}

## Output

Can be represented
Published on 27-Sep-2019 08:41:46