Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find XOR of all numbers in a given range

Tags:

algorithm

You are given a large range [a,b] where 'a' and 'b' can be typically between 1 and 4,000,000,000 inclusive. You have to find out the XOR of all the numbers in the given range.

This problem was used in TopCoder SRM. I saw one of the solutions submitted in the match and I'm not able to figure out how its working.

Could someone help explain the winning solution:

long long f(long long a) {      long long res[] = {a,1,a+1,0};      return res[a%4]; }  long long getXor(long long a, long long b) {      return f(b)^f(a-1); } 

Here, getXor() is the actual function to calculate the xor of all number in the passed range [a,b] and "f()" is a helper function.

like image 266
rajneesh2k10 Avatar asked May 20 '12 02:05

rajneesh2k10


People also ask

How do you find XOR of more than 2 numbers?

To find XOR of more than two numbers, represent all numbers in binary representation, add 0's before if necessary. Write them like this. and so on. To find each bit of XOR just calculate number of 1's in the corresponding bits.

What is XOR of same numbers?

XOR on the same argument: x ^ x = 0 If the two arguments are the same, the result is always 0 .


1 Answers

This is a pretty clever solution -- it exploits the fact that there is a pattern of results in the running XORs. The f() function calculates the XOR total run from [0, a]. Take a look at this table for 4-bit numbers:

0000 <- 0  [a] 0001 <- 1  [1] 0010 <- 3  [a+1] 0011 <- 0  [0] 0100 <- 4  [a] 0101 <- 1  [1] 0110 <- 7  [a+1] 0111 <- 0  [0] 1000 <- 8  [a] 1001 <- 1  [1] 1010 <- 11 [a+1] 1011 <- 0  [0] 1100 <- 12 [a] 1101 <- 1  [1] 1110 <- 15 [a+1] 1111 <- 0  [0] 

Where the first column is the binary representation and then the decimal result and its relation to its index (a) into the XOR list. This happens because all the upper bits cancel and the lowest two bits cycle every 4. So, that's how to arrive at that little lookup table.

Now, consider for a general range of [a,b]. We can use f() to find the XOR for [0,a-1] and [0,b]. Since any value XOR'd with itself is zero, the f(a-1) just cancels out all the values in the XOR run less than a, leaving you with the XOR of the range [a,b].

like image 195
FatalError Avatar answered Sep 28 '22 20:09

FatalError