首页 > 文章列表 > big.NewInt() 方法如何接受变量/参数传递?

big.NewInt() 方法如何接受变量/参数传递?

222 2024-02-06
问题内容

以下代码片段无法在 N := big.NewInt(n) 上编译,并出现以下错误:


cannot use n (variable of type int) as int64 value in argument to
big.NewInt
func Factorial(n int) *big.Int {
    var result = new(big.Int)
    i := new(big.Int)
    N := big.NewInt(n)
    for i.Cmp(N) < 0 {
        result = result.Mul(i, result)
        i = i.Add(i, new(big.Int))
    }
    return result
}

如果我传递一个 int64 文字(即 N := big.NewInt(1)),它就可以工作。但我需要一种方法将 int64 变量或参数/参数转换为 big.Int。我究竟做错了什么? Go 根本不支持这个吗?


正确答案


该错误是因为 https://pkg.go.dev/math/big# NewInt 函数采用 int64 值作为参数,而不是 int 类型。执行所需的类型转换:

N := big.NewInt(int64(n))

此外,计算逻辑可以非常简单地写为

func Factorial(n int) *big.Int {
    result, one := big.NewInt(1), big.NewInt(1)
    bigN := big.NewInt(int64(n))
    for bigN.Cmp(&big.Int{}) == 1 {
        result.Mul(result, bigN)
        bigN.Sub(bigN, one)
    }
    return result
}

https://go.dev/play/p/A-H-y10OwBb