7

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.

erasmo carlos
  • 664
  • 5
  • 16
  • 37
  • 3
    You are printing cumulative sums. 10 = 2 + 8, 44 = 10 + 34, 188 = 44 + 144, etc. In other words you are getting equivalent results to the spec, only producing different output. – Jon Mar 21 '16 at 21:20
  • Have you looked at all 288 results already on stack overflow? http://stackoverflow.com/search?q=Fibonacci+javascript – Charlie Mar 21 '16 at 21:25

4 Answers4

9

You are printing out the summation of even numbers. If you want to log each even fib number you need to log sum variable:

if (sum % 2 === 0) {
    evensum += sum;
    console.log(sum); // <---- log here
}
// console.log(evensum);
madox2
  • 49,493
  • 17
  • 99
  • 99
2

Simply move your console.log line outside of your while loop.

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

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

    console.log('Sum: ' + sum);
}

console.log('Full Sum of even Fibonacci numbers: ' + evensum);
ManoDestra
  • 6,325
  • 6
  • 26
  • 50
  • Hi ManoDestra, when I move the console.log outside the while, then I just get one value 3382 rather than the list. I need to show the list. Thank you. – erasmo carlos Mar 21 '16 at 21:26
  • Then just stick a console.log line inside the while loop to output the value of sum as well. Probably best to mark each output with some text before the values to qualify the difference. E.g. console.log('Sum : ' + sum); and console.log('Full Sum: ' + evensum); – ManoDestra Mar 21 '16 at 21:27
  • Thank you. I see what I was missing. – erasmo carlos Mar 21 '16 at 21:30
2

var i;
var fib = []; // Initialize array!

fib[0] = 0;
fib[1] = 1;
for(i=2; i<=20; i++)
{
    // Next fibonacci number = previous + one before previous
    // Translated to JavaScript:
    fib[i] = fib[i-2] + fib[i-1];
    if(fib[i]%2==0){
      document.write(fib[i]+" ");
    }
}
John
  • 760
  • 5
  • 12
2
var x = 0
var y = 1
var sum = 0;
var limit = 10000;
var evensum = 0;

while ((x + y) < limit) {
  sum = x + y;
  x = y;
  y = sum;
  if (sum % 2 == 0) {
  console.log(sum);
 }
}

working fiddle - https://jsfiddle.net/dotnojq8/1/

koolhuman
  • 1,581
  • 15
  • 25