Sum of Bitwise AND of all unordered triplets of an array | Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Traverse over all the bits ; Count number of elements with the current bit set ; There are ( cnt ) C ( 3 ) numbers with the current bit set and each triplet contributes 2 ^ bit to the result ; Return the resultant sum ; Driver Code
function tripletAndSum ( arr , n ) { let ans = 0 ; for ( let bit = 0 ; bit < 32 ; bit ++ ) { let cnt = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & ( 1 << bit ) ) cnt ++ ; } ans += ( 1 << bit ) * cnt * ( cnt - 1 ) * ( cnt - 2 ) / 6 ; } return ans ; } let arr = [ 3 , 5 , 4 , 7 ] ; let N = arr . length ; document . write ( tripletAndSum ( arr , N ) ) ;