- Recap of Last Time
- (In)efficiency of Recursion
- Magic of Recursion

- Looked at recursive methods for factorial and Fibonacci numbers
- Compared iterative and recursive solutions for Fibonacci

Iterative:

```
private static long iFactorial (long n) {
if (n <= 1) { return 1; }
long val = 1;
for (long i = 2; i <= n; i++) {
val *= i;
}
return val;
}
```

Recursive:

```
private static long rFactorial (long n) {
if (n <= 1) { return 1; }
return n * rFactorial(n - 1);
}
```

Recursive is more succinctâ€¦ but letâ€™s test their performance!

Iterative:

```
private static long iFib (long n) {
long prev = 0; long cur = 1; long next;
for (long count = 1; count < n; count++) {
next = prev + cur;
prev = cur;
cur = next;
}
return cur;
}
```

Recursive:

```
private static long rFib (long n) {
if (n <= 2) return 1;
return rFib(n-1) + rFib(n-2);
}
```

Why is this:

```
private static long rFactorial (long n) {
if (n <= 1) { return 1; }
return n * rFactorial(n - 1);
}
```

so much more efficient than this:

```
private static long rFib (long n) {
if (n <= 2) return 1;
return rFib(n-1) + rFib(n-2);
}
```

```
private static long rFactorial (long n) {
if (n <= 1) { return 1; }
return n * rFactorial(n - 1);
}
```

```
private static long rFib (long n) {
if (n <= 2) return 1;
return rFib(n-1) + rFib(n-2);
}
```

- The iterative solutions were efficient.
- Recursive factorials were efficient because no branching:
- each method call made only one recursive call

- Recursive Fibonacci was
*in*efficient because of branching:- each method call made 2 recursive calls
- even though few
*distinct*calls, all method calls executed as prescribed by code

- Extremely simple recursive methods
- Still simple iterative methods

Recall the Tower of Hanoi Puzzle:

- 3 pegs: 1, 2, 3
- stack of \(n\) disks of decreasing size on first peg
- can only move one peg at a time
- cannot put larger disk on top of a smaller disk

**Goal.** Move all disks from peg 1 to peg 3

All disks on first peg

Move one disk at a time

Cannot place a larger disk atop a smaller disk

To move all disks from peg 1 to peg 3

Want:

- A program that generates instructions for a solution
- Example solution for 2 disks

```
Move disk from peg 1 to peg 2
Move disk from peg 1 to peg 3
Move disk from peg 2 to peg 3
```

How do we design the program?

Hints:

- Think recursion!
- What has to happen before largest disk can be moved?

Discuss!