M
M
Marik Zukor2016-02-15 17:56:16
JavaScript
Marik Zukor, 2016-02-15 17:56:16

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

Why did the function return 55? the formula func(n - 1) + func(n-2) is obviously not a formula, because then it turns out func(9) + func(8), which means that 9 is 34 and 8 is 21, which in the end gives 55 since Fibonacci numbers 1(1),1(2),2(3),3(4),5(5),8(6),13(7),21(8),34(9) although you know that very well. But the question is different. Why did the interpreter count 9 as 34 and 8 as 21? this is not clear at all, even considering that the function takes this data from the call stack, but how they get there is a secret corner for me. Enlighten me, I will be extremely grateful!

Answer the question

In order to leave comments, you need to log in

6 answer(s)
D
dadster, 2016-02-15
@dadster

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)

K
kn1ght_t, 2016-02-15
@kn1ght_t

draw a stack of calls on a piece of paper and you will understand

D
Dmitry, 2016-02-15
@EvilsInterrupt

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

A
alexxandr, 2016-02-15
@alexxandr

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);
}

B
bromzh, 2016-02-15
@bromzh

Read the classics , at least the first 2-3 chapters, they explain everything on the fingers.
Well, look at pages 47-69.

A
Alisa94, 2019-06-13
@Alisa94

const zero = x => x === 0 ? 0 : res(x);
const one = y => y === 1 ? y : zero(y);
const res = z => z > 1 ? res(z - 1) + res(z - 2) : one(z);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question