Count pairs with set bits sum equal to K | C # 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
using System ; class GFG { static int MAX = 32 ; static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static int pairs ( int [ ] arr , int n , int k ) { int count = 0 ; int [ ] f = new int [ MAX + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) f [ countSetBits ( arr [ i ] ) ] ++ ; for ( int i = 0 ; i <= MAX ; i ++ ) { for ( int 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 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . Length ; int k = 4 ; Console . WriteLine ( pairs ( arr , n , k ) ) ; } }