Sum of Bitwise And of all pairs in a given array | 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  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
def pairAndSum ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , 32 ) : NEW_LINE INDENT k = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( arr [ j ] & ( 1 << i ) ) ) : NEW_LINE INDENT k = k + 1 NEW_LINE DEDENT DEDENT ans = ans + ( 1 << i ) * ( k * ( k - 1 ) // 2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 10 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( pairAndSum ( arr , n ) ) NEW_LINE