Number of pairs whose sum is a power of 2 | Function to return the count of valid pairs ; Storing occurrences of each element ; Start taking largest element each time ; If element has already been paired ; Find the number which is greater than a [ i ] and power of two ; If there is a number which adds up with a [ i ] to form a power of two ; Edge case when a [ i ] and crr - a [ i ] is same and we have only one occurrence of a [ i ] then it cannot be paired ; Remove already paired elements ; Return the count ; Driver Code
function countPairs ( a , n ) { let map = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { map . set ( a [ i ] , 1 ) ; } let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( map . get ( a [ i ] ) < 1 ) continue ; let cur = 1 ; while ( cur <= a [ i ] ) cur <<= 1 ; if ( map . has ( cur - a [ i ] ) ) { if ( cur - a [ i ] == a [ i ] && map . get ( a [ i ] ) == 1 ) continue ; count ++ ; map . set ( cur - a [ i ] , map . get ( cur - a [ i ] ) - 1 ) ; map . set ( a [ i ] , map . get ( a [ i ] ) - 1 ) ; } } return count ; } let a = [ 3 , 11 , 14 , 5 , 13 ] ; let n = a . length ; document . write ( countPairs ( a , n ) ) ;