duanqiao1880 2018-06-13 19:21
浏览 104
已采纳

为什么该程序溢出?

I have a small golang program that calculates the ith fibonnaci number, however it appears to overflow for some numbers large numbers, even when the array is changed to a type of int64. Why is this happening?

package main

import "fmt"

func main() {
    fib(555) //prints a negative number

}

func fib(num int) {

    queue := []int{0, 1}

    for i := 0; i < num; i++ {
        next := queue[0] + queue[1]
        queue[0] = queue[1]
        queue[1] = next
    }

    fmt.Println(queue[len(queue)-1])

}
  • 写回答

2条回答 默认 最新

  • douwen5681 2018-06-13 19:37
    关注

    The Fibonacci sequence gets very large, very fast. You need to use the math/big package in order to calculate integers this large. Translating your algorithm gives us:

    queue := []*big.Int{big.NewInt(0), big.NewInt(1)}
    
    for i := 0; i < num; i++ {
        next := new(big.Int).Add(queue[0], queue[1])
        queue[0] = queue[1]
        queue[1] = next
    }
    

    or more concisely:

    for i := 0; i < num; i++ {
        queue[0].Add(queue[0], queue[1])
        queue[0], queue[1] = queue[1], queue[0]
    }
    

    https://play.golang.org/p/udIITdDPfrY

    Which will output the following number with 555 as the input:

    70411399558423479787498867358975911087747238266614004739546108921832817803452035228895708644544982403856194431208467

    (this is off by 1 from the expected 555th Fibonacci number, since it's 0 indexed)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置