尝试使用递归来解决斐波那契(javascript) [英] Trying to Use Recursion to solve Fibonacci (javascript)
问题描述
这是问题:
给出正整数num,返回小于或等于num的所有奇数斐波纳契数的总和.
Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.
斐波那契数列中的前两个数字是1和1.序列中的每个其他数字是前两个数字的总和.斐波那契数列的前六个数字是1、1、2、3、5和8.
The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
例如,sumFibs(10)应该返回10,因为所有小于或等于10的斐波那契奇数均为1、1、3和5.
For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.
这是我尝试过的
function sumFibs(num, total = [1, 1], n = (total.length - 1 + total.length - 2)) {
if(n == num){
return total;
}
total.push(n);
sumFibs(num, n = (total.length - 1 + total.length - 2), total);
};
问题
是否可以使用我的方法来完成此工作,如果可以,该如何修复语法?如果没有,您将如何解决问题.
Is it possible to use my method to make this work, if so how do I fix the syntax? If not, how would you solve the problem.
非常感谢!
推荐答案
四件事
(1)您不返回递归调用的结果,因此它永远不会传递给调用者:
(1) You don't return the result of the recursive call, therefore it does never get passed up to the caller:
sumFibs(4, [1, 1]) -> sumFibs(4, [1, 1, 2]) -> sumFibs(4, [1, 1, 2, 3])
<- [1, 1, 2, 3]
// v the return you do
// v the return you need too
(2)在递归调用中,参数顺序错误.
(2) In the recursive call, the order of arguments is wrong.
(3)我想不是要使用数组长度减去1,而是要访问 total
数组中该位置的属性.
(3) I guess instead of taking the arrays length minus 1, you want to access the property at that position in the total
array.
(4)为什么您实际上 n
作为参数?由于它仅取决于 total
,因此也可以只是一个变量:
(4) Why do you actually n
as an argument? As it is only depending on total
, it could also just be a variable:
function sumFibs(num, total = [1, 1]) {
const n = total[total.length - 1] + total[total.length - 2];
if(n > num){
return total;
}
total.push(n);
return sumFibs(num, total);
}
console.log(sumFibs(19));
这篇关于尝试使用递归来解决斐波那契(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!