繁体   English   中英

我没有弄明白我的JavaScript代码有什么问题

[英]I don't get what's wrong with my Javascript code

我正在尝试解决Euler项目的第二个问题:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

这就是我尝试用Javascript解决的方式+为什么我认为这是合乎逻辑的:

var max = 4000000; //We create a variable with the maximum amount allowed, which is 4 million.
var result = 0; //Here we create a variable to store our result.

for (var i = 0; i < max; i++) //Now let's loop through the 4 million.
{
    if (i % 2 === 0) //We're checking for even numbers here because as I understood it, we have to only use the even numbers in this problem.
    {
        result = result + i; //Here we're adding "result" (Which is 0) to itself plus *i* (Which we're looping through!). We should have the result at the end of this loop.
    }
}

console.log(result); //Print our result.

我知道斐波那契数字会将行中的前一个数字加到自己,所以1 + 2将为3。

根据我的逻辑,这就是我对result = result + i所做的事情,但是我得到了错误的答案。

我在这里看不到逻辑。

并非每个低于4,000,000的偶数都在斐波那契数列中。 请尝试以下操作:

var max = 4000000, first = 1, second = 1, next = 0, result = 0;
while (second < max) {      // until we pass our limit
  next = first + second;    // find the next number in the fibonacci sequence by adding the previous two
  first = second;           // move on to the next numbers in the sequence
  second = next;
  if (second % 2 === 0)     // if the second number is even
    result += second;       // add it to our result
}
return result;              // result holds the sum of all the even fibonacci numbers below our limit!

暂无
暂无

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

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