Search code examples
javascriptfibonacci

Fibonacci Sequence (JS) - Sum of Even Numbers


I started Project Euler. I am on problem 2 and came up with this code to come up with the sum of even fibonacci numbers up to 4 million. The code seems to do pretty much what I want it to. I do see the correct sum listed when the code is ran. The only part I am really confused about is the very last number displayed in the results. This is what it shows:

JS CODE:

var previous = 0;
var current = 1;
var sum = 0;
var next;

   for(i = 1; i < 100; i++){
        next = current + previous;
        previous = current;
        current = next; 
        if(current % 2 === 0 && current < 4000000) {
            sum += current;
        console.log(sum);
        }
   }

RESULTS:

2
10
44
188
798
3382
14328
60696
257114
1089154
4613732 (this is the number i was trying to get)
=> 354224848179262000000 (confused as to why this number shows up and what it represents)

Solution

  • Let me break this down:

    Why does this show up?

    On the console, you will see the result of any expression you execute. If you execute a block of code you will see the last expression you executed in the block. Counter intuitively, in this case it is the result of current = next because the if statement is not run on your last time through the for loop.

    Why does next equal 354224848179262000000?

    The hundredth Fibonacci number is 354224848179261915075. JavaScript however loses precision as your numbers get past a certain point and starts assuming that all of the lower part of your number is zeros. See this question for move details: Why does JavaScript think 354224848179262000000 and 354224848179261915075 are equal?.