https://www.geeksforgeeks.org/sum-of-bitwise-or-of-all-possible-subsets-of-given-set/
Given an array arr[] of size n, we need to find sum of all the values that comes from ORing all the elements of the subsets.
Prerequisites : Subset Sum of given set
Input : arr[] = {1, 2, 3}
Output : 18
Total Subsets = 23 -1= 7
1 = 1
2 = 2
3 = 3
1 | 2 = 3
1 | 3 = 3
2 | 3 = 3
1 | 2 | 3 = 3
0(empty subset)
Now SUM of all these ORs = 1 + 2 + 3 + 3 +
3 + 3 + 3
= 18
A Naive approach is to take the OR all possible combination of array[] elements and then perform the summation of all values. Time complexity of this approach grows exponentially so it would not be better for large value of n.
An Efficient approach is to find the pattern with respect to the property of OR. Now again consider the subset in binary form like:
1 = 001 2 = 010 3 = 011 1 | 2 = 011 1 | 3 = 011 2 | 3 = 011 1|2|3 = 011
Insted of taking the OR of all possible elements of array, Here we will consider all possible subset with ith bit 1.
Now, consider the ith bit in all the resultant ORs, it is zero only if all the ith bit of elements in the subset is 0.
Number of subset with ith bit 1 = total possible subsets – subsets with all ith bit 0. Here, total subsets = 2^n – 1 and subsets with all ith bits 0 = 2^( count of zeros at ith bit of all the elements of array) – 1. Now, Total subset OR with ith bit 1 = (2^n-1)-(2^(count of zeros at ith bit)-1). Total value contributed by those bits with value 1 = total subset OR with ith bit 1 *(2^i).
Now, total sum = (total subset with ith bit 1) * 2^i + (total subset with i+1th bit 1) * 2^(i+1) + ……… + (total subset with 32 bit 1) * 2^32.
Now, consider the ith bit in all the resultant ORs, it is zero only if all the ith bit of elements in the subset is 0.
Number of subset with ith bit 1 = total possible subsets – subsets with all ith bit 0. Here, total subsets = 2^n – 1 and subsets with all ith bits 0 = 2^( count of zeros at ith bit of all the elements of array) – 1. Now, Total subset OR with ith bit 1 = (2^n-1)-(2^(count of zeros at ith bit)-1). Total value contributed by those bits with value 1 = total subset OR with ith bit 1 *(2^i).
Now, total sum = (total subset with ith bit 1) * 2^i + (total subset with i+1th bit 1) * 2^(i+1) + ……… + (total subset with 32 bit 1) * 2^32.