Count pairs with set bits sum equal to K | javascript implementation of the approach ; Function to return the count of set bits in n ; Function to return the count of required pairs ; To store the count ; Frequency array ; If current pair satisfies the given condition ; ( arr [ i ] , arr [ i ] ) cannot be a valid pair ; Driver code
var MAX = 32 ; function countSetBits ( n ) { var count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } function pairs ( arr , n , k ) { var count = 0 ; var f = Array . from ( { length : MAX + 1 } , ( _ , i ) => 0 ) ; for ( i = 0 ; i < n ; i ++ ) f [ countSetBits ( arr [ i ] ) ] ++ ; for ( i = 0 ; i <= MAX ; i ++ ) { for ( j = i ; j <= MAX ; j ++ ) { if ( i + j == k ) { if ( i == j ) count += ( ( f [ i ] * ( f [ i ] - 1 ) ) / 2 ) ; else count += ( f [ i ] * f [ j ] ) ; } } } return count ; } var arr = [ 1 , 2 , 3 , 4 , 5 ] ; var n = arr . length ; var k = 4 ; document . write ( pairs ( arr , n , k ) ) ;