为什么这个程序溢出?

时间:2018-06-13 19:21:14

标签: go integer-overflow

我有一个小的golang程序来计算$ openssl version OpenSSL 1.0.2g-fips 1 Mar 2016 $ openssl ciphers -v | grep DES | sort | head -5 DES-CBC3-SHA SSLv3 Kx=RSA Au=RSA Enc=3DES(168) Mac=SHA1 DH-DSS-DES-CBC3-SHA SSLv3 Kx=DH/DSS Au=DH Enc=3DES(168) Mac=SHA1 DH-RSA-DES-CBC3-SHA SSLv3 Kx=DH/RSA Au=DH Enc=3DES(168) Mac=SHA1 ECDH-ECDSA-DES-CBC3-SHA SSLv3 Kx=ECDH/ECDSA Au=ECDH Enc=3DES(168) Mac=SHA1 ECDHE-ECDSA-DES-CBC3-SHA SSLv3 Kx=ECDH Au=ECDSA Enc=3DES(168) Mac=SHA1 斐波纳西数,但是对于某些数字来说它似乎会溢出,即使数组更改为$ python --version Python 2.7.12 $ pip list asn1crypto (0.24.0) backports.ssl-match-hostname (3.5.0.1) cached-property (1.4.2) certifi (2018.4.16) cffi (1.11.5) chardet (3.0.4) crcmod (1.7) cryptography (2.2.2) docker (3.3.0) docker-compose (1.21.2) docker-pycreds (0.2.3) dockerpty (0.4.1) docopt (0.6.2) enum34 (1.1.6) functools32 (3.2.3.post2) idna (2.7) ipaddress (1.0.22) jsonschema (2.6.0) ndg-httpsclient (0.5.0) pip (8.1.2) psycopg2 (2.7.4) pyasn1 (0.4.3) pycparser (2.18) pyOpenSSL (18.0.0) python-apt (1.1.0b1) PyYAML (3.12) requests (2.19.0) setuptools (20.7.0) six (1.11.0) texttable (0.9.1) urllib3 (1.23) websocket-client (0.47.0) wheel (0.29.0) 类型也是如此。为什么会这样?

ith

2 个答案:

答案 0 :(得分:3)

Fibonacci序列变得非常大,速度非常快。您需要使用math/big包来计算这么大的整数。翻译算法给我们:

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
}

或更简洁:

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

将以555作为输入输出以下数字:

70411399558423479787498867358975911087747238266614004739546108921832817803452035228895708644544982403856194431208467

(从预期的第555个Fibonacci数字中减去1,因为它是0的索引)

答案 1 :(得分:0)

因为第555个斐波纳契数是

43516638122555047989641805373140394725407202037260729735885664398655775748034950972577909265605502785297675867877570

即使对于int64来说太大了。