How to implement Fibonacci number using recursion in JavaScript [duplicate]

南楼画角 提交于 2019-12-13 09:39:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!