- Intro to Recursion
- Activity: Fibonacci numbers
- Comparing Recursion and Iteration

- Lab 01, you use
*iteration*(looping) to solve a problem (printing something on the screen many times)`for int(i = 0; i < max; i++) { // do something }`

- Some problems are naturally
*recursive*: solution of the whole problem can be reduced to solving*the same*problem (possibly several times) on a smaller instance.`public int doSomething(int n) { // some code doSomething(n - 1); // recursive function call // some more code return something; }`

For a positive integer $n$, the factorial function, $f(n) = n!$ is defined to be:

- \[f(n) = n \cdot (n-1) \cdot (n - 2) \cdots 2 \cdot 1\]

Compute some factorials!

For any $n \geq 2$, we have

- \[f(n) = \begin{cases} 1 &\text{ if } n = 1\\ n \cdot f(n-1) &\text{ if } n > 1.\end{cases}\]

This is a *recursive formula*!

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

```
private static int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}
```

Compute `factorial(4)`

by hand!

The Fibonacci numbers are the sequence of numbers

$1, 1, 2, 3, 5, 8, 13, 21, \ldots$

where each number is the sum of the previous two.

**Activity.** Write a method that computes the $n$-th Fibonacci number for a positive integer (`long`

) $n$.

- Iterative (computation using a loop)
- Recursive

**Question.** Which is better?

What makes recursive Fibonacci slow, while recursive factorial is fairly fast?

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

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

Three morals, three questions

- Recursion may give simple code, but may be less efficient
- How can we determine which is better?

- Fibonacci numbers grow too fast
- How can we design a better solution?

- We should do better at error checking
- Can we validate input while running?