我的Javascript代码没有问题

时间:2014-11-13 22:41:01

标签: javascript

我正在尝试解决Project 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.

我知道Fibonacci数字会将行中的前一个数字添加到自身,因此1 + 2将为3。

根据我的逻辑,这就是我正在使用的result = result + i,但我得到了错误的答案。

我在这里看不到逻辑。

1 个答案:

答案 0 :(得分:1)

并非每个低于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!