简体   繁体   English

算法脚本:对所有奇数斐波那契数求和

[英]Algorithm Scripting: Sum All Odd Fibonacci Numbers

I am trying to solve this issue.我正在尝试解决这个问题。

" Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num. " 给定一个正数 integer num,返回所有小于或等于 num 的奇数斐波那契数的总和。

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.斐波那契数列中的前两个数是 1 和 1。数列中的每个附加数都是前两个数的和。 The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.斐波那契数列的前六个数字是 1、1、2、3、5 和 8。

For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5."例如,sumFibs(10) 应该返回 10,因为所有小于或等于 10 的奇数斐波那契数都是 1、1、3 和 5。”

This was my solution, and I just can't understand why it satisfies all the statements except the last one.这是我的解决方案,我只是不明白为什么它满足除最后一个之外的所有陈述。 I can't find the mistake.我找不到错误。 I would appreciate any help!我将不胜感激任何帮助!

function sumFibs(num) {
  if(num === 1){
    return 1;
  }else if(num ===2){
    return 2;
  }

let arr=[1,1],
curr =1,
prev =1;

for(let i = 2; i<num;i++){
  let next = curr + prev;
  prev = curr;
  curr= next;
  
  if(curr<num && curr%2!==0){
      arr.push(curr);    
  }
}

   return arr.reduce((a,b)=>a+b);
}

console.log(sumFibs(75024));
console.log(sumFibs(75025));

It's giving me the same result for both even when they should be different.即使它们应该不同,它也给了我相同的结果。

在此处输入图像描述

You are supposed to add numbers that are "less or equal to num".您应该添加“小于或等于 num”的数字。 You are summing only numbers < num.您只对数字 < num 求和。

The mistake appears to be the conditional statement if(curr<num && curr%2!==0) which does't satify the instructions above which say as follows: return the sum of all odd Fibonacci numbers that are less than or equal to num错误似乎是条件语句if(curr<num && curr%2!==0)不满足上面的说明,说明如下:返回小于或等于的所有奇数斐波那契数的总和数

Therefore when we use if(curr<num && curr%2!==0) as our conditional statement we do not include 75025 since it doesn't represent a number less than the variable num.因此,当我们使用if(curr<num && curr%2!==0)作为条件语句时,我们不包括 75025,因为它不代表小于变量 num 的数字。

That is where we find the mistake.这就是我们发现错误的地方。 It should include numbers that are not only less but also the ones that are equal to num , in this case num being 75025, which wasn't being include in the group of odd Fibonacci numbers to sum up, due to the incorrect conditional statement.它应该包括不仅小于而且等于num的数字,在这种情况下num是 75025,由于不正确的条件语句,它没有被包括在要总结的奇数斐波那契数组中。

You are only considering numbers less than num, but the task description says less than or equal.您只考虑小于 num 的数字,但任务描述说小于或等于。 The base case for 1 is also wrong. 1 的基本情况也是错误的。 Actually you don't need the base cases at the beginning.实际上,您一开始并不需要基本案例。 And instead of the for loop you should use a while loop.而不是 for 循环,您应该使用 while 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM