You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift自底向上实现斐波那契函数时出现Runtime Error问题

问题原因分析
  • 首先排除递归栈溢出问题:你实现的是自底向上的迭代写法,全程没有递归调用,完全不存在栈溢出的可能。
  • 实际错误根源是整数溢出:Swift的Int是和平台绑定的有符号整数类型,64位系统下最大可存储值为9223372036854775807,而斐波那契数列第93项的值就已经超过这个上限,n=100时数值远大于Int可承载范围,Swift默认对整数溢出会直接触发运行时错误,也就是你遇到的EXC_BAD_INSTRUCTION报错。
  • 附加优化提示:你代码里的if bottom_up.isEmpty判断是冗余逻辑,每次调用函数时都会重新初始化空的bottom_up数组,这个判断永远为真,没有实际作用。
修复方案

如果只需要计算93项以内的斐波那契值,可以用UInt64替换Int扩大承载范围,同时优化冗余代码:

func computeFiboBottomUp(n: Int) -> UInt64 {
    guard n > 0 else { return 0 }
    if n == 1 || n == 2 { return 1 }
    // 直接初始化指定长度的数组,避免可选类型开销
    var bottom_up = [UInt64](repeating: 0, count: n + 1)
    bottom_up[1] = 1
    bottom_up[2] = 1
    for i in 3...n {
        bottom_up[i] = bottom_up[i-1] + bottom_up[i-2]
    }
    return bottom_up[n]
}

如果需要计算n=100甚至更大的斐波那契值,可以使用Decimal类型支持更大的数值存储:

func computeFiboBottomUpLarge(n: Int) -> Decimal {
    guard n > 0 else { return 0 }
    if n == 1 || n == 2 { return 1 }
    var bottom_up = [Decimal](repeating: 0, count: n + 1)
    bottom_up[1] = 1
    bottom_up[2] = 1
    for i in 3...n {
        bottom_up[i] = bottom_up[i-1] + bottom_up[i-2]
    }
    return bottom_up[n]
}

内容的提问来源于stack exchange,提问作者Junsu Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:54:00