Sum of Bitwise AND of all unordered triplets of an array | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int tripletAndSum ( int arr [ ] , int n ) { int ans = 0 ; for ( int bit = 0 ; bit < 32 ; bit ++ ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & ( 1 << bit ) ) cnt ++ ; } ans += ( 1 << bit ) * cnt * ( cnt - 1 ) * ( cnt - 2 ) / 6 ; } return ans ; } int main ( ) { int arr [ ] = { 3 , 5 , 4 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << tripletAndSum ( arr , N ) ; return 0 ; }