Fibonacci Sequence (JS) - Sum of Even Numbers

I launched Project Euler. I am on problem 2 and came up with this code to come up with even a Fibonacci amount of up to 4 million. The code seems to do pretty much what I want. I see the correct amount indicated when running the code. The only part that I really confuse is the most recent number displayed in the results. Here is what he 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) 
+6
source share
2 answers

Let me break this:

Why is this displayed?

On the console, you will see the result of executing any expression. If you execute a block of code, you will see the last expression that you executed in the block. The counter is intuitive, in this case it is the result of current = next , because the if statement does not run for the last time through the for loop.

Why is the next level equal to 354224848179262000000?

The hundredth Fibonacci number is 354224848179261915075. However, JavaScript loses accuracy since your numbers go past a certain point and begin to assume that the entire lower part of your number is zeros. See this question for relocation details: Why does JavaScript think that 354224848179262000000 and 354224848179261915075 are equal? .

+6
source

You can use this code to solve your problem, and the algorithm does not need to go through 100 iterations to get an answer (this is your modification, the difference is in the for loop when you use the current variable for iteration):

  function sumFibs(num) { let previous = 0; let current = 1; let sum = 0; let next; for(current; current <= num;){ next = current + previous; previous = current; if(current % 2 === 0) { sum += current; } current = next; } return sum; } sumFibs(4000000); // return 4613732 
0
source

All Articles