Maths WorkshopMaths problems with full solutions
Exercise 1312Combinatorics › Counting principlesM1Added 5 Nov 2026

Nim and the XOR rule

#combinatorial games#Nim#XOR#binary

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 (3,4,5)(3,4,5)?

Hint

Show that from XOR =0=0 every move produces XOR ≠0\ne0, and that from XOR ≠0\ne0 there is a move to XOR =0=0 (look at the leading bit of the XOR).

Show solutionHide solution

Solution

Idea. Call a position *balanced* if the XOR ss of the pile sizes is 00. Show that balanced positions are exactly the losing ones.

Balanced to unbalanced. If the position is balanced and a pile aa is replaced by a′<aa'<a, the new XOR is a⊕a′≠0a\oplus a'\ne0.

Unbalanced to balanced. Let s≠0s\ne0 and let tt be the position of its leading bit. Some pile aa has bit tt set. Replace aa by a′=a⊕sa'=a\oplus s. Since ss has leading bit tt and aa has that bit equal to 11, flipping it makes a′<aa'<a, so removing a−a′a-a' stones is legal, and the new XOR is s⊕a⊕a′=0s\oplus a\oplus a'=0.

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. 3⊕4⊕5=2≠03\oplus4\oplus5=2\ne0. The pile 33 has the bit of value 22: replace it by 3⊕2=13\oplus2=1, i.e. remove 22 stones. The position (1,4,5)(1,4,5) has XOR 00 ✓.

Lesson. For impartial games, find the invariant set of losing positions and prove the two closure properties.