## Nim

Nim: finitely many piles of coins; a move comprises removing a positive number
of coins from a single pile; a player loses if they can't move.

Remark:
    For any nim position $P$, either it can be won by the player with the move,
    or it can be won by the player without the move.

    i.e. one of the two players has a "winning strategy", a way to play which
    guarantees a win.

\newcommand{\caret}{\mathbin{\char`\^}}
The "nim sum", $n (+) m$, of natural numbers $n$ and $m$ is the result of writing
the binary expansions of $n$ and $m$ and "adding without carrying". (In computer
science, this is called "XORing the bitstrings"; in many programming
languages, it's written as "{\tt n\char`\^ m}".)

Theorem:
    The player without the move can win from the Nim position with piles of
    sizes $n_1,...,n_k$
    iff $n_1 (+) n_2 (+) ... (+) n_k = 0$
Proof:
    Suppose inductively that this is true for all nim positions with fewer
    coins involved.

    First, suppose
    :	$n_1 (+) n_2 (+) ... (+) n_k = b != 0$.
    We show that we can win if we have the move.

    Consider binary expansions.
    Some $n_i$ has a 1 in the same position as the leading 1 of $b$,
    so
    :	$n_i (+) b < n_i$.

    So we can move by taking coins from the ith pile so as to leave $n_i (+)
    b$ coins in that pile.

    Then in the new position, the nim sum of the pile sizes is
    :	$n_1 (+) ... (+) n_{i-1} (+) n_i (+) b (+) n_{i+1} (+) ... (+) n_k$
    :	$= b (+) b$
    :	$= 0$

    So by the induction hypothesis, the player without the move wins from
    here. But that's us!

    Now suppose 
    :	$n_1 (+) n_2 (+) ... (+) n_k = 0$
    and we don't have the move.

    If our opponent can't move, we've won.
    Else, suppose they move by taking coins from the ith pile, leaving $m < n_i$.
    But then $m (+) n_i != 0$, so
    :	$n_1 (+) ... (+) m (+) ... (+) n_k != n_1 (+) ... (+) n_i (+) ... n_k = 0$,
    so by the induction hypothesis, we're left with a position won by the
    player with the move, which is us.
