2014-11-13 114 views
0

我試圖解決肚裏項目歐拉的第二個問題:我不明白有什麼錯我的Javascript代碼

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

按照我的邏輯,這就是我與做,但我得到了錯誤的答案。

我看不到這裏的邏輯。

+0

您正在添加_all_偶數。你已經排除了通過斐波那契數列推進的位置。 – brycem

+0

你正在尋找我的價值觀。這會給你斐波那契數列中的偶數嗎? (提示:否) –

+0

就像brycem和Oliver說的那樣:你將所有偶數加在1到4百萬之間。首先需要找到斐波那契數列,然後再把所有偶數列相加。 –

回答

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! 
+0

你能解釋一下這個邏輯嗎?我不明白爲什麼這會起作用,以及它如何添加斐波納契數字。 – SstrykerR

+0

我已經更新了我的答案。希望它更有幫助! –

+0

這絕對是美麗的。謝謝! – SstrykerR

相關問題