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.
Recursive Sequence: Definition The famous Fibonacci sequence. This famous sequence is recursive because each term after the second term is the sum of the previous two terms. Our first two terms are 1 and 1. The third term is the previous two terms added together, or 1 + 1 = 2.
The recurrence relation for the Fibonacci numbers is a second-order recurrence, meaning it involves the previous two values. It is also linear homogeneous, meaning that every term is a constant multiplied by a sequence value. In general, one can write this as: g(n) = ag(n − 1) + bg(n − 2).
This function is instructive as a prototypical tree recursion, but it is a terribly inefficient way to compute Fibonacci numbers because it does so much redundant computation. The entire computation of fib(3) is duplicated.
Fibonacci numbers grow exponentially and normally a computer can iterate around 10^8 - 10^9 values of n in one seconds. If you will execute a recursive function, may be the function is taking lots of values because of which the program is executing slowly.
Recursion is like this:
source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With