Given an array A, consisting of N non-negative integers, find the sum of xor of all unordered triplets of the array. For unordered triplets, the triplet (A[i], A[j], A[k]) is considered same as triplet (A[j], A[i], A[k]) and all the other permutations.
Since the answer can be large calculate its mod with 10037.
Input : A = [3, 5, 2, 18, 7] Output : 132 Input : A = [140, 1, 66] Output : 207
Iterate over all the unordered triplets and add xor of each to the sum.
- An important point to observe is that xor is independent over all the bits. So we can do the required computation over each bit individually.
- Let’s consider the k’th bit of all the array elements. If the number of unoredered triplets whose k’th bit xor to 1 be C, we can simply add C * 2k to the answer. Let the number of elements whose k’th bit is 1 be X and whose k’th bit is 0 be Y. Then to find the unordered triplets whose k’th bits xor to 1 can be formed using two cases:
- Only one of the three elements have k’th bit 1.
- All three of them have k’th bit 1.
- Number of ways to select 3 element having k’th bit 1 =
- Number of ways to select 1 element with k’th bit 1 and rest with 0 =
- We will use nCr mod p to compute the combinotorial function values.
Below is the implementation of the above approach.
Time Complexity : O(32 * N)