Nim and the XOR rule
Statement
In the game of Nim there are several piles of stones. Two players alternately remove any positive number of stones from one pile; the player who cannot move loses. Prove that the player to move wins if and only if the bitwise XOR of the pile sizes is non-zero. Which move wins from ?
Hint
Show that from XOR every move produces XOR , and that from XOR there is a move to XOR (look at the leading bit of the XOR).
Show solutionHide solution
Solution
Idea. Call a position *balanced* if the XOR of the pile sizes is . Show that balanced positions are exactly the losing ones.
Balanced to unbalanced. If the position is balanced and a pile is replaced by , the new XOR is .
Unbalanced to balanced. Let and let be the position of its leading bit. Some pile has bit set. Replace by . Since has leading bit and has that bit equal to , flipping it makes , so removing stones is legal, and the new XOR is .
Conclusion. The terminal position is balanced. A player facing a balanced position can only move to unbalanced positions; so the player facing a balanced position loses. ∎
Example. . The pile has the bit of value : replace it by , i.e. remove stones. The position has XOR ✓.
Lesson. For impartial games, find the invariant set of losing positions and prove the two closure properties.