Check if a number can be expressed as 2^x + 2^y 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


 Live Demo

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


Can be represented
Published on 27-Sep-2019 11:53:18