凡人斐波那契兔 - 值大于 6 时的误差



我试着数一数凡人的斐波那契兔子。该任务假设兔子在固定的几个月后死亡。

图为兔子数量如何随时间变化 兔子

凡人兔子的斐波那契数列如下所示:

{1,1,2,2,3,4,5,7,9,12,16,21,28 (...(}

我的代码很简单 - 不幸的是只计到 6(含(。

function rabbits(n){
if (n<=2){
return 1
}
else if (n===3 || n===4){
return 2
}
else {
f1 = 1
f2 = 1
f3 = 2
f4 = 2
for (i = 5; i <= n; i++) {
f = f2 + f3
f3 = f2
f2 = f
}
return f
}
}

console.log(rabbits(1)) // 1
console.log(rabbits(2))  //1 
console.log(rabbits(3))  // 2
console.log(rabbits(4))  //2
console.log(rabbits(5))  //3
console.log(rabbits(6))  //4
console.log(rabbits(7))  //7
console.log(rabbits(8))  //11
console.log(rabbits(9))  //18
console.log(rabbits(10)) //29

从 7 向上 - 而不是 F (n-2( + F (n-3( - 计数 F (n-1( + (F (n-2(。

我不知道为什么会这样。错误在哪里?

我刚刚开始使用JS进行冒险,我担心我无法理解复杂的代码(什么和为什么( - 所以我寻求建议/帮助修改现有的代码,以便初学者理解。

编辑//

好的,问题解决了。这是一个工作代码:

var Fib=[]
for(i=1;i<=n;i++){
if(i===1||i===2){
Fib.push(1)
}
else if(i===3|| i===4){
Fib.push(2)
}
else{
fib=Fib[Fib.length-2]+Fib[Fib.length-3]
Fib.push(fib)
}
}
console.log(Fib)

我不确定获得"斐波那契数"的正确论坛,我使用了维基百科中的那个。

无论如何,我认为您可以使用数组来获取以前的值,请参阅以下内容:

function rabbits(n){
let fib = [];
for(let i=1; i<=15; i++){
fib.push(i+i-1);
}
return fib[n-1];
}
for(let i=1; i<=10; i++){
console.log("rabbits("+ i + ") = ", rabbits(i));
}
<span>From Wikipedia:</span>
<cite>
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones.
</cite>

最新更新