wtetzner wrote:The Fibonacci sequence is defined as:
Code: Select all
fib(0) = 1
fib(1) = 1
fib(n) = (n - 2) + (n - 1) for n > 1
(Note that the above is not code, just the mathematical definition.)
What this says is that fib(0) returns 1, fib(1) returns 1, and for every integer n that is above 1, fib(n) returns the sum of the previous two values in the sequence.
So let's compute fib(2).
Code: Select all
Now, fib(n) = fib(n - 2) + fib(n - 1)
Then fib(2) = fib(2 - 2) + fib(2 - 1)
So fib(2) = fib(0) + fib(1)
fib(2) = 1 + 1, since fib(0) = 1 and fib(1) = 1
So when you write the function in code, you need to check if n = 0 or if n = 1. These are called the
base cases or
termination conditions. That's because they are not defined in terms of fib, so when you get a value n that is 0 or 1, it stops the recursion.
Everything else is defined in terms of fib.
Say you call fib with n = 4.
So fib(4) = fib(4 - 2) + fib(4 - 1)
Then fib(4) = fib(2) + fib(3)
Now fib(2) and fib(3) need to be computed in order to find fib(4).
So we compute fib(2):
fib(2) = fib(2 - 2) + fib(2 - 1)
fib(2) = fib(0) + fib(1)
So now we need to compute fib(0) and fib(1) to find fib(2)
But both fib(0) and fib(1) return 1. These are the base cases, since they don't call fib again.
So now we can finish computing fib(2).
fib(2) = fib(0) + fib(1)
fib(2) = 1 + 1
fib(2) = 2
Now we need fib(3) to finish computing fib(4), which we started computing above.
So fib(3) = fib(3 - 2) + fib(3 - 1)
fib(3) = fib(1) + fib(2)
Now we need to compute fib(1) and fib(2) to find fib(3).
fib(1) is a base case, and returns 1.
Computing fib(2) is the same as fib(2) above, which we discovered returns 2.
So fib(3) = fib(1) + fib(2)
fib(3) = 1 + 2
fib(3) = 3
Now we know both fib(2) and fib(3), so we can finish computing fib(4)
fib(4) = fib(2) + fib(3)
fib(4) = 2 + 3
fib(4) = 5
Hopefully I wasn't too unclear. The example was kind of long, but if you follow each step, you should be able to understand the process.