Problem 715
XOR of Numbers from L to R
Easy · 10 pts · Bit Manipulation, Math
Problem
Compute L XOR (L + 1) XOR ... XOR R. Looping is too slow when the range is huge. The XOR of all numbers from 0 to n follows a cycle of length 4: it equals n when n mod 4 = 0, 1 when n mod 4 = 1, n + 1 when n mod 4 = 2, and 0 when n mod 4 = 3. The XOR of the range is then xorTo(R) XOR xorTo(L - 1), because the numbers below L cancel out.
Input
A single line with two integers L and R.
Output
Print the XOR of all integers from L to R.
Constraints
1 <= L <= R <= 10^9
Example input
3 5
Example output
2
Explanation
For L = 3 and R = 5, 3 XOR 4 = 7 and 7 XOR 5 = 2, so the answer is 2. The formula agrees: xorTo(5) = 1, xorTo(2) = 3, and 1 XOR 3 = 2.