Number of pairs whose sum is a power of 2 | Set 2 | Function to count all pairs whose sum is a power of two ; Stores the frequency of each element of the array ; Update frequency of array elements ; Stores count of required pairs ; Current power of 2 ; Traverse the array ; If pair does not exist ; Increment count of pairs ; Return the count of pairs ; Driver Code
function countPair ( arr , n ) { var m = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( m . has ( arr [ i ] ) ) m . set ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) else m . set ( arr [ i ] , 1 ) } var ans = 0 ; for ( var i = 0 ; i < 31 ; i ++ ) { var key = Math . pow ( 2 , i ) ; for ( var j = 0 ; j < n ; j ++ ) { var k = key - arr [ j ] ; if ( ! m . has ( k ) ) continue ; else ans += m . get ( k ) ; if ( k == arr [ j ] ) ans ++ ; } } return ans / 2 ; } var arr = [ 1 , 8 , 2 , 10 , 6 ] var n = arr . length document . write ( countPair ( arr , n ) ) ;