如何在JavaScript中使用递归实现斐波那契数 [英] How to implement Fibonacci number using recursion in JavaScript

查看:103
本文介绍了如何在JavaScript中使用递归实现斐波那契数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在javascript中玩递归.我为斐波那契数列编写了一个函数.但是,仅当参数为0时有效

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

它返回1表示1,但大于0的数字表示错误超出了最大调用堆栈大小

It returns 1 for 1, but a number above 0 I get the error maximum call stack size exceeded

推荐答案

您需要倒数第二次迭代的值,而不需要前面的迭代.

You need the value of the second last iteration, no an iteration ahead.

也请在这里看看:斐波那契编号.

const fib = x => {
    if (x === 0 || x === 1) {
        return 1;
    }
    return fib(x - 2) + fib(x - 1);
};

console.log(fib(7));

这篇关于如何在JavaScript中使用递归实现斐波那契数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆