Home >Backend Development >Golang >How to pass variables/parameters to big.NewInt()
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>
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 }
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?
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))
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 }
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!