Fibonacci Sequence (JS) - Sum of Even Numbers

早过忘川 提交于 2019-12-05 07:36:15
skyler

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?.

You can use this code to fix your problem, with this the algorithm don't need to go through 100 iterations to reach your answer (Is a modification of yours, the difference is in the for loop, when you use the current variable for the 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!