gpt4 book ai didi

go - big.Int slice 在 append() 上重写自身

转载 作者:IT王子 更新时间:2023-10-29 01:57:19 29 4
gpt4 key购买 nike

我正在尝试获取 3 和 i 的平方根之间的奇数的一部分 big.Ints

当我运行以下代码时:

import (
"fmt"
"math/big"
)

func main() {
i := big.NewInt(101)
var divisorsOfPrime []*big.Int
squareRoot := big.NewInt(0).Sqrt(i)
for n := big.NewInt(3); n.Cmp(squareRoot) == -1; n.Add(n, big.NewInt(2)) {
divisorsOfPrime = append(divisorsOfPrime, n)
}
fmt.Println(divisorsOfPrime)
}

我得到输出:

[11 11 11 11]

但我希望输出:

[3 5 7 9 11]

我该怎么做才能解决这个问题?

谢谢

最佳答案

您有一片 *big.Int,您在其中一遍又一遍地存储相同的指针。

相反,您需要在每次迭代时存储 n 的副本。

替换:

divisorsOfPrime = append(divisorsOfPrime, n)

与:

nCopy := new(big.Int).Set(n)
divisorsOfPrime = append(divisorsOfPrime, nCopy)

顺便说一句,这不是*big.Int特有的;只要您正在处理指针,就需要创建新对象并将指针存储到这些新对象,而不是原始对象。请注意,n 只分配了一次。

关于go - big.Int slice 在 append() 上重写自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044036/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com