Nim Game Strategy: The Maths Trick to Always Win
Nim is an ancient two-player game played with piles of sticks, stones or coins. Players take turns removing any number of objects from a single pile, and in the usual version the player who takes the last object wins. What makes Nim special is that it has a complete mathematical solution, published by the mathematician Charles Bouton in 1901. Once you know it, you can win almost every time.
The rules (our version)
The classic board starts with four rows of 1, 3, 5 and 7 sticks (our game also uses a few other starting layouts). On your turn you take one or more sticks from one row. Whoever takes the very last stick wins.
Step 1: Write the rows in binary
Binary numbers use only 0 and 1. Each place stands for 4, 2 or 1 in small numbers like these:
| Row | Sticks | 4s | 2s | 1s |
|---|---|---|---|---|
| A | 1 | 0 | 0 | 1 |
| B | 3 | 0 | 1 | 1 |
| C | 5 | 1 | 0 | 1 |
| D | 7 | 1 | 1 | 1 |
Step 2: Count each column
Count the 1s in each column. In the starting position: the 4s column has two 1s, the 2s column has two 1s and the 1s column has four 1s. Every column has an even count.
Step 3: Always leave every column even
This is the whole secret. A position where every column has an even number of 1s is a losing position for the player about to move. Whatever they do, at least one column becomes odd, and you can always make a move that turns every column even again. Eventually you take the last stick.
Mathematicians call this the nim-sum: the result of combining the row sizes with the binary operation XOR. A nim-sum of zero means "every column is even".
What this means for the starting position
Because 1, 3, 5, 7 already has every column even, the player who moves first is in a losing position if the opponent plays perfectly. In our game you always move first, so when the classic 1-3-5-7 layout appears the Hard computer can always win. Our game also deals other starting layouts - check the columns before your first move: if any column is odd, you can win by making them all even.
An example
Suppose the rows are 0, 3, 5, 7 after a few moves. The columns are: 4s = two (5 and 7), 2s = two (3 and 7), 1s = three (3, 5 and 7). The 1s column is odd, so you are in a winning position. Take one stick from any row with a 1 in the 1s column - for example make 7 into 6. Now every column is even again.
A quick shortcut
Two equal rows always cancel each other out. If only two rows are left and they are equal, mirror your opponent: whatever they take from one row, take the same from the other.
Try it in Matchstick Nim. If you enjoy maths-based games, also play Number Guess (which uses binary search) and the Tower of Hanoi.


