text: Sum of Bitwise And of all pairs in a given array | An efficient C ++ program to compute sum of bitwise AND of all pairs ; Returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; Traverse over all bits ; Count number of elements with i 'th bit set  int k = 0; Initialize the count ; There are k set bits , means k ( k - 1 ) / 2 pairs . Every pair adds 2 ^ i to the answer . Therefore , we add "2 ^ i ▁ * ▁ [ k * ( k - 1 ) / 2 ] " to the answer . ; Driver program to test above function
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int pairAndSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) if ( ( arr [ j ] & ( 1 << i ) ) ) k ++ ; ans += ( 1 << i ) * ( k * ( k - 1 ) / 2 ) ; } return ans ; } int main ( ) { int arr [ ] = { 5 , 10 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << pairAndSum ( arr , n ) << endl ; return 0 ; }