Professional Documents
Culture Documents
Introduction
The Tower of Hanoi is a mathematical puzzle invented by E Lucas in1883. It consists of
three pegs, and a number of disks of different sizes which can slide onto any peg. The puzzle
starts with the disks neatly stacked in order of size on one peg, the smallest at the top, thus
making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following
rules:
• Only one disk may be moved at a time.
• Each move consists of taking the upper disk from one of the rods and sliding it onto
another rod, on top of the other disks that may already be present on that rod.
• No disk may be placed on top of a smaller disk.
Mathematical Model
Here we assume that there are three pages named Source(S), Intermediate(I) and
Destination(D). Our aim is to move a tower of n disks from a starting peg S onto a destination
peg D, I being the remaining third peg and assuming S≠D.
If there is only one disk (or even none at all), the problem is trivial. If n=1, then simply move
the disk from peg S to peg D. If n>1, then somewhere along the sequence of moves, the
largest disk must be moved from peg S to another peg, preferably to peg D. The only
situation that allows this move is when all smaller n-1 disks are on peg I. Hence, first all h-1
smaller disks must go from S to D. Subsequently move the largest disk and finally move the
n-1 smaller disks from peg I to peg D. Now the problem is reduced to moving n-1 disks from
one peg to another one, first from S to I and subsequently from I to D, but the same method
can be used both times by renaming the pegs.
In the implementation of Tower of hanoi, the user is prompted to input the number of plates
and that integer is stored in a variable n. The following is a procedure for moving a tower of n
disks from a peg S onto a peg D, with T being the remaining third peg:
• Step 1: If n>1 then first use this procedure to move the n-1 smaller disks from peg S
to peg D.
• Step 2: Now the largest disk, i.e. disk can be moved from peg S to peg D.
• Step 3: If n>1 then again use this procedure to move the n-1 smaller disks from peg S
to peg D.
Algorithm
Hanoi(n: integer; source, intermediate, destination)
Begin
1. if (n=1) then
a) write: SOURCE DESTINATION.
b) Return.
[End of If structure]
4. Return.
Source Code
➢ Time Analysis
No. of moves = 2n – 1
ts = 0.00278424313
= 0.000214172 seconds
= 18,446,744,073,709,551,615 *
0.000214172
No. of disks
= 3,950,776,071,754,522.08848778
seconds
= 4,572,657,490.566227876015 days
= 4,572,657,490.21437602664296365.242199 years
No.12,519,521.30047923631804374280421
= of disks
years
= 18,446,744,073,709,551,615 seconds
= 213,503,982,334,601.29184027days
= 213,503,982,334,601.29184027365.242199 years
= 584,554,530,991.0952864465635 years