Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tail recursion and fibonacci

I was looking at this site: http://rosettacode.org/wiki/Fibonacci_sequence#JavaScript and saw this program:

function fib(n) {
  return function(n,a,b) {
    return n>0 ? arguments.callee(n-1,b,a+b) : a;
  }(n,0,1);
}

How does this work, what are those two arguments (a and b) help. I traced it and still can't figure out how this works

like image 395
qwertymk Avatar asked Jul 29 '11 18:07

qwertymk


People also ask

Is Fibonacci algorithm tail recursion?

Write a tail recursive function for calculating the n-th Fibonacci number. A recursive function is tail recursive when the recursive call is the last thing executed by the function. Recommended: Please try your approach on {IDE} first, before moving on to the solution.

How does Fibonacci work in recursion?

The function fibonacci is called recursively until we get the output. In the function, we first check if the number n is zero or one. If yes, we return the value of n. If not, we recursively call fibonacci with the values n-1 and n-2.

Is the Fibonacci sequence recursion?

The famous Fibonacci sequence. This famous sequence is recursive because each term after the second term is the sum of the previous two terms.

What is tail recursion?

Definition: A special form of recursion where the last operation of a function is a recursive call. The recursion may be optimized away by executing the call in the current stack frame and returning its result rather than creating a new stack frame.


1 Answers

In the function(n,a,b), n serves as a countdown counter, and a b stores two consecutive Fibonacci numbers for the purpose of computing the next, so when n reaches 0, you have a as the n+1-th Fibonacci number (since the real Fibonacci has two 1s as the beginning).

E.g., n=4:

n  a  b
4  0  1
3  1  2
2  2  3
1  3  5
0  5  8

As you can see, the value of a and b always equal to the Fibonacci numbers. Also, this is very similar to Functional Programming (as the website stated Scheme programmers).

like image 175
zw324 Avatar answered Sep 23 '22 09:09

zw324