Pairs from an array that satisfy the given condition | Function to return the number of set bits in n ; Function to return the count of required pairs ; Set bits for first element of the pair ; Set bits for second element of the pair ; Set bits of the resultant number which is the XOR of both the elements of the pair ; If the condition is satisfied ; Increment the count ; Return the total count ; Driver code
function setBits ( n ) { let count = 0 ; while ( n > 0 ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } function countPairs ( a , n ) { let count = 0 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { let setbits_x = setBits ( a [ i ] ) ; for ( let j = i + 1 ; j < n ; j ++ ) { let setbits_y = setBits ( a [ j ] ) ; let setbits_xor_xy = setBits ( a [ i ] ^ a [ j ] ) ; if ( setbits_x + setbits_y == setbits_xor_xy ) count ++ ; } } return count ; } let a = [ 2 , 3 , 4 , 5 , 6 ] ; let n = a . length ; document . write ( countPairs ( a , n ) ) ;