问题
I tried playing around with recursion in javascript. I wrote a function for the Fibonacci sequence. However, if only works if the argument is 0
fib = (x)=>{
if (x == 0 || x ==1) {
return 1
} else {
return fib(x-1) + fib(x+1)
}
}
It returns 1 for 1, but a number above 0 I get the error maximum call stack size exceeded
回答1:
This is not the Fibonacci sequence. This is the Fibonacci sequence:
fib = (x) => {
if (x == 0 || x == 1) {
return 1;
} else {
return fib(x - 1) + fib(x - 2);
}
}
for (let i = 0; i < 10; i++) {
console.log(fib(i));
}
In its simplest form, of course. If you go too far beyond 10, you'll experience what an exponential cost of computation can do to a computer.
回答2:
You need the value of the second last iteration, no an iteration ahead.
Please have a look here, too: Fibonacci number.
const fib = x => {
if (x === 0 || x === 1) {
return 1;
}
return fib(x - 2) + fib(x - 1);
};
console.log(fib(7));
来源:https://stackoverflow.com/questions/55657978/how-to-implement-fibonacci-number-using-recursion-in-javascript