Nim game

Take any number of sticks from one row. Whoever takes the last stick wins. The bot plays perfectly, but every game starts in your favor: find the winning move and keep finding it.

Click a stick to take it and every stick to its right in that row.

The winning strategy, step by step

Take rows of 3, 4 and 5 sticks. In binary those are 011, 100 and 101. XOR them, column by column: an odd number of 1s gives 1, an even number gives 0.

  3 = 011
  4 = 100
  5 = 101
  ───────
XOR = 010  (2)

The nim-sum is 2, not 0, so the player to move can win. The winning move is the one that makes it 0: change the row of 3 (011) to 011 XOR 010 = 001, which means taking 2 sticks and leaving 1. Now it's 1, 4, 5, and 001 XOR 100 XOR 101 = 000. Whatever your opponent does next breaks the zero, and you restore it.

This works because a position with nim-sum 0 can only move to a nonzero one, a nonzero position always has a move back to 0, and the final position, no sticks at all, has nim-sum 0. So whoever keeps handing over zeros takes the last stick.

Common questions

How do you play Nim?

There are a few rows of sticks. On your turn, take as many sticks as you like (at least one) from a single row. Whoever takes the last stick wins. (In the "misère" version the last stick loses; this page plays the normal version.)

What is the winning strategy for Nim?

Write each row's count in binary and combine them with XOR, adding each binary column without carrying: an odd number of 1s gives 1, an even number gives 0. That total is called the nim-sum. If it's 0 at the start of your turn you are losing against perfect play; if not, there is always a move that makes it 0, and if you keep doing that you win.

Who solved Nim?

Mathematician Charles L. Bouton published the complete solution in 1901, in the journal Annals of Mathematics, and gave the game its name. In the 1930s Roland Sprague and Patrick Grundy showed that a whole family of similar games can be reduced to Nim.

Can I beat the bot?

Yes. Every game here starts with a nonzero nim-sum, so the first player (you) can always win with perfect play. One slip, though, and the bot takes over. Turn on "Show the math" to see the nim-sum as you play.

More games