JavaScript Coding Challenge #3

Hello,

Today we’re going to play with the fibonacci numbers:

I’d love to hear your feedback!

1 Like

I put a comment on your article, but I thought I would share the same over here.

A less complicated version would skip creating that large array (extra memory) and then iterating over it to get the sum. Using only a running sum of the even numbers in the series, use the following which runs using only O(1) space to generate the series. My version may also be simplified with some more thought.

function fibSeries() {
 var prev =1;
 var next = 2;
 var evenSum = 2;
 while (next < 4000000) {
   var temp = next;
   next += prev;
   prev = temp;
   if (next % 2 === 0) evenSum += next;
 }
 return evenSum;
}

UPDATE: corrected while loop as pointed out by @Flopet17

1 Like

Very nice @rmdawson71!
But as I said in the response on medium, in your while loop you don’t need:

next + prev < 4000000

But instead:

next < 4000000

This will return indeed the right answer! :smile:

I corrected my function above. I had already copied/pasted the original code, before I got your comment on the other site.

1 Like

Oh. I see! :smiley: Well done!