5

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...

Paweł
  • 51

1 Answers1

0

I think some of the proofs are based on observations and generalizing the patterns. It helps at many places where you can't prove things using a theorem but things can be sorted out using observations.

Euler's Polyhedral Formula $ V(vertices) + F(faces) - E(edges) = 2$ is such an example. Euler did not give a proper proof (though it was proved in many ways afterwards), this result inspired huge advances.

EDIT: There are a lot of threads with the same question and everyone solved it using mere observation. One of the threads can be found here.

Daga
  • 291