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 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
function isPowerOfTwo ( n ) { return n != 0 && ( ( n & ( n - 1 ) ) == 0 ) ; } function previousPowerOfTwo ( n ) { while ( ( n & n - 1 ) > 1 ) { n = n & n - 1 ; } return n ; } function checkSum ( n ) { if ( n == 0 n == 1 ) return false ; else if ( isPowerOfTwo ( n ) ) { document . write ( n / 2 + " " + n / 2 + " " ) ; } else { var x = previousPowerOfTwo ( n ) ; var y = n - x ; if ( isPowerOfTwo ( y ) ) { document . write ( x + " " + y + " " ) ; return true ; } } return false ; } var n1 = 20 ; if ( checkSum ( n1 ) == false ) document . write ( " " ) ; document . write ( ) ; var n2 = 11 ; if ( checkSum ( n2 ) == false ) document . write ( " " ) ;