Answer the question
In order to leave comments, you need to log in
Fibonacci numbers in JS (recursion). How does the function work?
function func(n) {
return n <= 1 ? n : func(n - 1) + func(n - 2);
}
alert(func(10)); // 55
Answer the question
In order to leave comments, you need to log in
It expands further to the end (the function calls itself recursively) until it returns something. (i.e., until the condition n <= 1 is met, and n is returned.
To simplify, let's look at f(5)
f(5) = f(4) + f(3) -> expand further function calls with new parameters, it turns out:
( f(3) + f(2) ) + ( f(2) + f(1) ) -> here for f(1) the value (1) already appears, But for exponentiality, let's expand everything to the end:
( ( f(2) + f(1) ) + ( ( f(1) + f(0) ) + ( ( f(1) + f(0) ) + f(1), there is only 1 call left, for f(2), all others return specific digits, f(1) = 1, f(0) = 0. f(2) = f(1) + f(0) = 1.
It turns out 1 + 1 + 1 + 0 + 1 + 0 + 1 = 5.
The same sweep can be done for f (10), all of which will also be reduced to a set of units that add up to 55.
I hope the question was precisely in this, and not in the mechanism of recursion in JS, if so, then I have nothing prompt)
make improvements to the function:
1. Pass the recursion level
2. Decrease the level on exit
3. Increase the level on entry
4. Also output a number at the given recursion level
Will be clear and understandable
pogromists school jesters
int f(int n)
{
if (n <= 0) return 0;
else if (n == 1) return 1;
else return f(n-1) + f(n-2);
}
Read the classics , at least the first 2-3 chapters, they explain everything on the fingers.
Well, look at pages 47-69.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question