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.
var x = 0;
var i;
var max = 4000000;
var sequence = [1,2];
var totalSum = 2; //start at two since I consider the first even number in array.
while(x <= max)
{
x = 0;
for(i = 0; i < 2; i++)
{
x = x + sequence[i];
}
if(x % 2 == 0) //check whether the number is even or odd
{
totalSum = totalSum + x; //if even, it's added to the total sum
}
sequence.shift(); //these two lines allow the sequence to shift
sequence.push(x); //with numbers generated by each cycle
}
document.getElementById("result").innerHTML = totalSum;
The solution is fairly simple to understand. We have to add up all the even numbers that are present in the Fibonacci sequence until the addend is less or equal to 4 million.
To do so, we are going to check whether a number is even or odd by using the % operator. If even, it will be added to the total, otherwhise it will be discarded.
This will keep going until the condition in the while cycle is false (which occurs when the addend is greater than 4 million).
To keep track of the numbers in the Fibonacci sequence, we use an array of 2 numbers. We only need to know the past and current number in order to generate the next.
The series starts at 0,1 and then proceeds at 1,1 and then 1,2. We only need to consider the 1,2 pair since that's where the first even number appears.
The result calculated from the code on the left is: