The following code snippet is failing to compile on N := big.NewInt(n) with the following error:
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
}
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 parameter/argument to a big.Int. What am I doing wrong? Does Go not support this at all?
The error is because the https://pkg.go.dev/math/big#NewInt function takes an
int64value as the argument and not aninttype. Do the required type conversion asMoreover the computation logic can very simply written as
https://go.dev/play/p/A-H-y10OwBb