I was trying to calculate integer xor of 0..n. I named the function xored(n).
Note that in examples below ^ does not mean power but integer xor (like in C or Java language)
So, xored(0) = 0, xored(1) = 0 ^ 1, xored(2) = 0 ^ 1 ^ 2, xored(3) = 0 ^ 1 ^ 2 ^ 3, etc...
Or, if you prefer recursive definition:
xored(0) = 0
xored(n) = n ^ xored(n-1)
First, I created a naive implementation that that loops through the values and xors them together.
Then, I noticed a funny thing. I noticed a pattern with my results.
All you need to do is to calculate n modulo 4 (call it m) then:
if m = 0, xored(n) = n
if m = 1, xored(n) = 1
if m = 2, xored(n) = n + 1
if m = 3, xored(n) = 0
My question is. Why does it work? How can this be proven mathematically? I am not good at proving theorems...