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
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.
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.
The famous Fibonacci sequence. This famous sequence is recursive because each term after the second term is the sum of the previous two terms.
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.
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).
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