JavaScript: calculate the sum of all even numbers in Fibonacci sequence values < 10000

Viewed 3625

I have to complete this exercise, and I am not getting the results I need.

The specifications are: Calculate the sum of all even numbers in a Fibonacci sequence for values under 10,000. The first few numbers summed would be: 2, 8, 34, 144, 610.

I have a fiddle that produces this output: 10, 44, 188, 798, 3382.

var x = 1;
var y = 2;
var sum = 0;
var limit = 10000;
var evensum = 2;

while ((x + y) < limit) {
    sum = x + y;
    x = y;
    y = sum;

    if (sum % 2 === 0) {
        evensum += sum;
    }
    console.log(evensum);
}

fiddle link

Could someone please help me figuring out the part I am missing to complete this exercise?

Thank you much.

UPDATE Thank you everyone who posted a solution. They all worked great.

4 Answers
Related