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

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

Specifications: Calculate the sum of all even numbers in the Fibonacci sequence for values ​​less than 10,000. The first few sums are summed: 2, 8, 34, 144, 610 .

I have a violin that produces this conclusion: 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); } 

script link

Can someone please help me deal with the part that I am missing to complete this exercise?

Many thanks.

UPDATE Thanks to everyone who posted the solution. They all worked great.

+7
source share
4 answers

You print the summation of even numbers. If you want to register every even number of the fix, you need to register the variable sum :

 if (sum % 2 === 0) { evensum += sum; console.log(sum); // <---- log here } // console.log(evensum); 
+8
source

Just move the line console.log outside the 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); 
+1
source

 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]+" "); } } 
+1
source
 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/

+1
source

All Articles