Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fibonacci numbers, why does this recurring function work?

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.

like image 476
Joseph Avatar asked Nov 03 '10 23:11

Joseph


People also ask

Why is Fibonacci series considered a recursive function?

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.

Can you apply recurrence in Fibonacci?

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).

Why is recursive Fibonacci inefficient?

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.

Why is the straightforward recursive implementation of the Fibonacci sequence slow?

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.


1 Answers

Recursion is like this:

  1. A child couldn't sleep, so her mother told her a story about a little frog,
  2. who couldn't sleep, so the frog's mother told her a story about a little bear,
  3. who couldn't sleep, so the bear's mother told her a story about a little weasel...
  4. who fell asleep.
  5. ..and the little bear fell asleep;
  6. ...and the little frog fell asleep;
  7. ...and the child fell asleep.

source

like image 53
tpae Avatar answered Sep 17 '22 13:09

tpae