According to the myth of the Towers of Hanoi, many centuries ago in the city of Hanoi, the monks in a certain monastery were continually engaged in what now seems a peculiar enterprise. Sixty-four rings of increasing size had been placed on a vertical wooden peg (Figure 17.16). Beside this peg were two other pegs. The monks spent their time attempting to move all the rings from the first to the third peg—subject to two constraints:

Only one ring could be moved at a time.

A ring could be moved to any peg, provided it was not placed on top of a smaller ring.

According to the legend, the monks believed that the world would end and humankind would be freed from suffering when the task was finally completed. The world is still here today and you are enduring the frustrations of writing computer programs, which seems to indicate that the monks were interrupted in their work. But even if they had stuck with it, they would not have finished anytime soon. A little experimentation should convince you that for n rings, 2n – 1 separate moves are required. At the rate of one move per second, 264 – 1 moves would take about 600 billion years.

It might be more practical to harness the incredible processing power of modern computers to move virtual rings between virtual pegs. To get started, write a recursive function for printing the required moves. In the spirit of moderation, we suggest that you begin by running the program for small values of n. Figure 17.17 shows the result of running the program with three rings. In the output, the rings are numbered from smallest (1) to largest (3). Run the program with different numbers of rings to satisfy yourself that the printed output is correct. The number of lines of output corresponds to the formula given earlier.

The program uses a recursive function called move that expects four arguments: the number of disks; and numbers representing the first, third, and second pegs (in that order). The first time this function is called, it is asked to move all n rings from peg 1 to peg 3, using peg 2 as temporary working storage. The function then proceeds by doing the following: it calls itself to move the top n – 1 rings to peg 2: it prints a message to move the largest ring from peg 1 to peg 3: and, finally, it calls itself again to move the n – 1 rings from peg 2 to peg 3.