How to pass variables/parameters to big.NewInt()

WBOY
Release: 2024-02-05 22:18:04
forward
802 people have browsed it

如何将变量/参数传递给 big.NewInt()

Question content

The following code snippet fails to compile on N := big.NewInt(n) with the following error :

<code>
cannot use n (variable of type int) as int64 value in argument to
big.NewInt
</code>
Copy after login
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
}
Copy after login

If I pass an int64 literal (i.e. N := big.NewInt(1)) it works. But I need a way to convert an int64 variable or argument/argument to big.Int. What did I do wrong? Doesn't Go support this at all?


Correct answer


This error is because https://pkg.go.dev/math/big# NewInt function uses int64 value as argument, not int type. Perform the required type conversion:

N := big.NewInt(int64(n))
Copy after login

In addition, the calculation logic can be written very simply as

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
}
Copy after login

https://www.php.cn/link/861f8aa2598860c0023f399e992eb747

The above is the detailed content of How to pass variables/parameters to big.NewInt(). For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template