代码之家  ›  专栏  ›  技术社区  ›  MaxCodes

大的Int slice在append()上重写自身

  •  2
  • MaxCodes  · 技术社区  · 7 年前

    我想从中分一杯羹 big.Ints 3到的平方根之间的奇数 i .

    当我运行以下代码时:

    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]
    

    我能做些什么来解决这个问题?

    谢谢

    1 回复  |  直到 7 年前
        1
  •  4
  •   Marc    7 年前

    你有一片 *big.Int 在其中反复存储同一指针。

    相反,您需要存储 n 在每次迭代中。

    替换:

    divisorsOfPrime = append(divisorsOfPrime, n)
    

    使用:

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

    顺便说一下,这不是特定于 *大的。内景 ; 只要处理指针,就需要创建新对象并存储指向这些新对象的指针,而不是原始对象的指针。请注意 n 只分配一次。