Fibonacci序列(JS) - 偶数之和 [英] Fibonacci Sequence (JS) - Sum of Even Numbers

查看:126
本文介绍了Fibonacci序列(JS) - 偶数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创办了Project Euler。我遇到了问题2并提出了这个代码来得出甚至斐波那契数字达到400万的总和。代码似乎完全符合我的要求。我确实看到代码运行时列出了​​正确的总和。我真正感到困惑的唯一部分是结果中显示的最后一个数字。这就是它所显示的:

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代码:

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);
        }
   }

结果:

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)


推荐答案

让我打破这个:

在控制台上,您将看到您执行的任何表达式的结果。如果执行一段代码,您将看到在块中执行的最后一个表达式。与此直观相反,在这种情况下,它是 current = next 的结果,因为if语句不会在上一次通过for循环运行。

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.

第100个斐波纳契数是354224848179261915075.但是当你的数字超过某一点并开始时,JavaScript会失去精确度假设你的数字的所有下半部分都是零。有关移动详情,请参阅此问题:为什么JavaScript会考虑354224848179262000000和354224848179261915075是平等的吗?

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

这篇关于Fibonacci序列(JS) - 偶数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆