# Discussion Assignment #8: Computing Fibonacci Numbers

### 2 November 2011

As we begin our brief study of recursion, we will look at a famous example of a recursively defined sequence of integers, the Fibonacci sequence. (This was first described in the Western literature in 1202 by Leonardo of Pisa, though it was apparently known earlier in India.)

We define the Fibonacci numbers F(i), for i = 0, 1, 2, ..., by the three rules:

1. F(0) = 0

2. F(1) = 1

3. if n > 1, then F(n) = F(n-1) + F(n-2)

This is a recursive definition because Rule 3 defines some values of the sequence in terms of others. We can see that F(2) = F(1) + F(0) = 1 + 0 = 1, and that F(3) = F(2) + F(1) = 1 + 1 = 2. Similarly we can compute F(4) = 3 and F(5) = 5. For any non-negative integer n, our recursion will be grounded -- we will eventually reach the base cases of F(0) and F(1), and be able to complete our computation without further recursion.

here is a recursive static method to compute the function `fib` that takes input n and returns F(n):

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

### Exercises:

Question 1: Trace the `fib` method above to compute the value of F(7). Do not cut corners -- indicate exactly what method calls will be made by the code, even if you think they are a bad idea.

Question 2: Estimate the time needed for the `fib` method above to calculate F(n), in terms of either n itself or of F(n).

Question 3: Calculate the value of F(20). You may use any method, but show your work.

Question 4: Write a method, recursive or not, to calculate F(n) in O(n) time.