Check if a number can be expressed as 2 ^ x + 2 ^ y | CPP code to check if a number can be expressed as 2 ^ x + 2 ^ y ; Utility function to check if a number is power of 2 or not ; Utility function to determine the value of previous power of 2 ; function to check if n can be expressed as 2 ^ x + 2 ^ y or not ; if value of n is 0 or 1 it can not be expressed as 2 ^ x + 2 ^ y ; if a number is power of 2 then it can be expressed as 2 ^ x + 2 ^ y ; if the remainder after subtracting previous power of 2 is also a power of 2 then it can be expressed as 2 ^ x + 2 ^ y ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int n ) { return ( n && ! ( n & ( n - 1 ) ) ) ; } int previousPowerOfTwo ( int n ) { while ( n & n - 1 ) { n = n & n - 1 ; } return n ; } bool checkSum ( int n ) { if ( n == 0 n == 1 ) return false ; else if ( isPowerOfTwo ( n ) ) { cout << " ▁ " << n / 2 << " ▁ " << n / 2 ; return true ; } else { int x = previousPowerOfTwo ( n ) ; int y = n - x ; if ( isPowerOfTwo ( y ) ) { cout << " ▁ " << x << " ▁ " << y ; return true ; } } return false ; } int main ( ) { int n1 = 20 ; if ( checkSum ( n1 ) == false ) cout << " No " ; cout << endl ; int n2 = 11 ; if ( checkSum ( n2 ) == false ) cout << " No " ; return 0 ; }