I'm trying to solve Project Euler's second problem which goes:
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.
And this is how I tried to solve it in Javascript + Why I think it's logical:
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.
I know that Fibonacci numbers add the previous number in the row to themselves, so 1 + 2 would be 3.
According to my logic, that's what I'm doing with result = result + i, yet I'm getting the wrong answer.
I can't see the logic here.