我試圖解決肚裏項目歐拉的第二個問題:我不明白有什麼錯我的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
按照我的邏輯,這就是我與做,但我得到了錯誤的答案。
我看不到這裏的邏輯。
您正在添加_all_偶數。你已經排除了通過斐波那契數列推進的位置。 – brycem
你正在尋找我的價值觀。這會給你斐波那契數列中的偶數嗎? (提示:否) –
就像brycem和Oliver說的那樣:你將所有偶數加在1到4百萬之間。首先需要找到斐波那契數列,然後再把所有偶數列相加。 –