简单的 Swift Fibonacci 程序崩溃(Project Euler 2) [英] Simple Swift Fibonacci program crashing (Project Euler 2)

查看:28
本文介绍了简单的 Swift Fibonacci 程序崩溃(Project Euler 2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决 Project Euler 上的第二个问题.问题如下:

I am trying to solve the second problem on Project Euler. The problem is as follows:

斐波那契数列中的每个新项都是通过将前两项相加而生成的.从 1 和 2 开始,前 10 项将是:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...通过考虑斐波那契数列中值不超过 400 万的项,求偶数值项的总和.

我想我已经写了一个解决方案,但是当我尝试运行我的代码时,它使我的 Swift Playground 崩溃并给了我这个错误消息:

I think I've written a solution, but when I try to run my code it crashes my Swift playground and gives me this error message:

Playground 执行中止:执行被中断,原因:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Playground execution aborted: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

<小时>

var prev = 0
var next = 1
var num = 0
var sum = 0

for var i = 1; i < 400; i++ {
    num = prev + next
    if next % 2 == 0 {
        sum += next
    }
    prev = next
    next = num
}
print(sum)

<小时>

奇怪的是,如果我将循环中的计数器设置为小于 93,它就可以正常工作.将变量名显式设置为 Double 无济于事.有人知道这里发生了什么吗?


The weird thing is, if I set the counter on my loop to less than 93, it works fine. Explicitly setting the variable names to Double does not help. Anyone know what's going on here?

推荐答案

这根本没有什么奇怪.你知道400斐波那契数有多大吗?

There is nothing weird about this at all. Do you know how large the 400 fibonacci number is?

176023680645013966468226945392411250770384383304492191886725992896575345044216019675

Swift Int64UInt64 根本无法处理这么大的数字.后者最高可以达到 18446744073709551615 - 甚至不接近.

Swift Int64 or UInt64 simply cannot handle that large of a number. The later can go up to 18446744073709551615 at max - not even close.

如果您将变量更改为双精度,它会起作用,但会不准确:

If you change your variables to be doubles it works but will be inaccurate:

var prev : Double = 0
var next : Double = 1
var num : Double = 0
var sum : Double = 0

会产生

2.84812298108489e+83

2.84812298108489e+83

这有点接近

1.76e+83

幸运的是,您不需要获得那么大的值.我建议不要编写 for 循环,而是编写 while 循环来计算下一个斐波那契数,直到满足中断条件其值不超过四百万.

Luckily you do not need to get values that big. I would recommend not writing a for loop but a while loop that calculates the next fibonacci number until the break condition is met whose values do not exceed four million.

这篇关于简单的 Swift Fibonacci 程序崩溃(Project Euler 2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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