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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址