big.Int切片将自己重写在append()上

I am trying to get a slice of big.Ints of the odd numbers between 3 and the square root of i.

When I run the following code:

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)
}

I get the output:

[11 11 11 11]

But I expect the output:

[3 5 7 9 11]

What can I do to fix this?

Thanks

You have a slice of *big.Int in which you store the same pointer over and over again.

Instead, you need to store a copy of n on each iteration.

Replace:

divisorsOfPrime = append(divisorsOfPrime, n)

With:

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

By the way, this is not specific to *big.Int; as long as you're handling pointers you need to create new objects and store pointers to those new objects, not the original one. Notice that n is assigned exactly once.