8

I hesitated to post on StackOverflow but I think the problem has little to do with programming and more to do with mathematics. So, here it is:

I wanted to compute the function $ f(n) = 0 \oplus 1 \oplus 2 \oplus \dotsb \oplus n$ in O(1) instead of O(n) so I computed $f(1), f(2),...$ to see the global look of the function and it appears that it has an easily identifiable pattern, which can be used to transform $f$ like so:

$$ f(n) = \left\{ \begin{array}{ll} n & \mbox{if } n \equiv 0 \pmod 4 \\ 1 & \mbox{if } n \equiv 1 \pmod 4 \\ n+1 & \mbox{if } n \equiv 2 \pmod 4 \\ 0 & \mbox{if } n \equiv 3 \pmod 4 \\ \end{array} \right. $$

Does anyone know why the function has such pattern ?

Cranium
  • 183

1 Answers1

7

That's very interesting. It is also simple to prove using induction:

  • Demonstrate that it's true for $0$. $f(0) = 0$. Done.
  • Assume true for all integers $n$ where $0 \leq n \leq 4N$ for some $N \geq 0$.
  • Show that this assumption implies the conjecture is true for $4N+1$, $4N+2$, $4N+3$ and for $4N+4$.

For $n = 4N+1$, note that low bit of $4N$ is zero, so $n = 4N+1 = 4N \oplus 1$. We assumed $f(n-1) = 4N$, so $f(n) = 4N \oplus (4N \oplus 1) = 1$.

For $n = 4N+2$, note that the low bit of $4N + 2$ is also zero, so $1 \oplus (4N+2) = 4N + 3$, which is $n+1$.

For $n = 4N+3$, $f(n-1) = 4N+3$, so $f(n) = (4N+3) \oplus (4N+3) = 0$.

For $n = 4N+4$, $f(n-1) = 0$, thus $f(n) = 0 \oplus (4N+4) = 4N+4 = n$.

QED

user3294068
  • 1,272