Advertisement
RaFiN_

Xor of all subsets of a given set of size n

Nov 9th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. /* Xor of all subsets of a given set of size n */
  2.  
  3. /* Understand like this. Consider ith bit of all inputs. Count the number of 1's and the number of 0's. So suppose at the ith bit we have K 1's and N-K 0's. Then out of all 2^n subsets, those subsets which have odd number of 1's will give 1 as XOR output at the ith bit and the other subsets will give zero. Now you can prove that independent of K, exactly 2^(n-1) subsets will have odd number of ones. (provided K>0)
  4.  
  5. Proof : KC1*2^(N-K) + KC3*2^(N-K) + ... = 2^(K-1) * 2^(N-K) = 2^(N-1)
  6.  
  7.    (KC1 is the usual Combinatoric i.e. K!/1!(K-1)!)*/
  8.  
  9. /*Solution: Find the OR of all the elements and multiply it with 2^(n-1) where n is the total number of elements. This gives us the answer.
  10.  
  11. Idea:
  12.  
  13. There will be a total of 2^n subsets.
  14. If ith bit of any element is set, then that bit will be set in the xor of half of the total subsets which is 2^(n-1).
  15. To find out all of the set bits in all of the numbers we find the OR of all of the numbers.
  16. Since each set bit appears in half of the total subsets, we multiply the OR of all of the numbers with 2^n-1 to get the final result */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement