I have to plete 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 plete this exercise?
Thank you much.
UPDATE Thank you everyone who posted a solution. They all worked great.
I have to plete 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 plete this exercise?
Thank you much.
UPDATE Thank you everyone who posted a solution. They all worked great.
Share Improve this question edited Mar 21, 2016 at 21:40 erasmo carlos asked Mar 21, 2016 at 21:18 erasmo carloserasmo carlos 6826 gold badges17 silver badges48 bronze badges 2- 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 Commented Mar 21, 2016 at 21:20
- Have you looked at all 288 results already on stack overflow? stackoverflow./search?q=Fibonacci+javascript – Charlie Commented Mar 21, 2016 at 21:25
4 Answers
Reset to default 9You 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);
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]+" ");
}
}
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);
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/dotnojq8/1/