- 2068 Magh · 8 marks
Recursion properties, Fibonacci, TOH algorithm
Short answer
Properties: self-call, base case, smaller subproblem, stack frames, results combined while returning. Recursive Fibonacci is not preferred because it repeats subproblems: fib(30) makes 2,692,537 calls, O(2^n) time and O(n) stack. TOH for three disks: A->C, A->B, C->B, A->C, B->A, B->C, A->C, total 7 moves.
State properties of recursion. Why is the recursive method for Fibonacci sequence not preferred? Write an algorithm for TOH problem and use it to find the solution for three disks.
Properties of recursion
- A recursive function calls itself, directly or indirectly.
- It has a base case (stopping condition) whose answer is known without further calls.
- Each recursive call works on a smaller or simpler version of the problem and moves toward the base case.
- Every call has its own parameters, local variables and return address, stored on the stack.
- The result is built while returning (unwinding) from the calls.
- Without a reachable base case the recursion is infinite and ends in stack overflow.
Why recursive Fibonacci is not preferred
fib(n) = fib(n-1) + fib(n-2), fib(0) = 0, fib(1) = 1. The same sub-problems are solved again and again: in fib(5), fib(3) is computed twice and fib(2) three times. The number of calls grows exponentially (fib(5): 15 calls, fib(30): 2,692,537 calls, counted by program), time is O(2ⁿ), and stack depth is n. An iterative loop gives the answer in n steps with constant memory.
TOH algorithm
TOH(n, from, to, aux):
- If n = 1, move disk 1 from
fromtotoand return. - TOH(n-1, from, aux, to).
- Move disk n from
fromtoto. - TOH(n-1, aux, to, from).
Solution for 3 disks: TOH(3, A, C, B)
| Move | Disk | From | To | Pegs after the move (A / B / C) |
|---|---|---|---|---|
| 1 | 1 | A | C | 3,2 / - / 1 |
| 2 | 2 | A | B | 3 / 2 / 1 |
| 3 | 1 | C | B | 3 / 2,1 / - |
| 4 | 3 | A | C | - / 2,1 / 3 |
| 5 | 1 | B | A | 1 / 2 / 3 |
| 6 | 2 | B | C | 1 / - / 3,2 |
| 7 | 1 | A | C | - / - / 3,2,1 |
Total 2³ − 1 = 7 moves.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Recursion, Fibonacci and TOH · Data Structure and Algorithm, chapter 5
- TOH problem with solution for n disks · Data Structure and Algorithm, chapter 5 · asked 2×
- Tree recursion and TOH with n disks · Data Structure and Algorithm, chapter 5
- TOH algorithm and recursion tree · Data Structure and Algorithm, chapter 5 · asked 2×
- TOH for 3 disks and recursion principle · Data Structure and Algorithm, chapter 5
- Solve TOH for 3 disks · Data Structure and Algorithm, chapter 5 · asked 2×
- Multipath inheritance problem and solution · Object Oriented Programming, chapter 6 · asked 2×
- Recursive language and its properties · Theory of Computation, chapter 4 · asked 2×