I’m going through a programming book and one of the examples is about fibonacci numbers, and how a recurring function finds the fibonacci number for the nth one along.
The code looks like this:
Int fib (int n)
{
If (n<3)
Return (1);
Else
Return (fib(n-1))+(fib(n-2))
}
Now this isn’t exact because I’m typing from my phone and I have a understanding how the code is working, it’s calling itself until it returns 1, then it’s adds up the return values until you have the correct fibonacci number for the position in the sequence.
So I don’t need help with the code. What I do need help with is understanding why this works. How does adding all the returns give the correct answer?
Please can someone explain why this is working. Thanks. It’s driving me mad.
A Fibonacci number is defined as the sum of the two preceding Fibonacci numbers. That gives the following:
So for the 3rd number (1 1 2) you would take the result of finding the previous – i.e. 2nd (1 1 2) number and add it to the number before the previous – i.e. 1st (1 1 2) number.
You also have to understand that the program needs to calculate the value of the two preceding numbers before it can calculate the number you want to know. Therefore it keeps calling itself – using the same method – until it has calculated everything.