All games

Tower of Hanoi

0 moves

Move every disk to the right peg. No larger disk on a smaller one. How to solve

4 disks · Fewest 15 · 0:00

How to play the Tower of Hanoi

Minimum number of moves

With n disks, the minimum number of moves is 2n − 1 (2 multiplied by itself n times, minus 1). Each extra disk roughly doubles the number of moves.

DisksFewest moves
37
415
531
663
7127
8255
9511
101,023

Why? Look at the largest disk. Before it can move to the right peg, all n − 1 disks above it have to be out of the way on the middle peg. Then the largest disk moves to the right in one move, and the n − 1 disks go back on top of it. So n disks take “moves for n − 1 disks × 2 + 1”: 3 disks take 3 × 2 + 1 = 7 moves, 4 disks take 7 × 2 + 1 = 15 moves, and so on.

How to solve the Tower of Hanoi

The recursive solution

The block idea is the classic example of recursion in programming. To move n disks, move n − 1 disks to the spare peg, move the largest disk, then move the n − 1 disks onto it:

function hanoi(n, from, to, spare) {
  if (n === 0) return;
  hanoi(n - 1, from, spare, to);
  move(from, to);
  hanoi(n - 1, spare, to, from);
}

About the Tower of Hanoi

The Tower of Hanoi was invented by the French mathematician Édouard Lucas and first presented in 1883, as a game supposedly found by “N. Claus de Siam” (an anagram of Lucas d’Amiens). It came with a legend: in a temple in Benares, priests are moving the 64 golden disks of the Tower of Brahma, and when they finish, the world will end. Moving 64 disks takes at least 18,446,744,073,709,551,615 moves. At one move per second, that is about 585 billion years. Today the puzzle is a favorite in math and programming classes, and psychologists use it to study problem solving.