gomathnumericfactorial

How do I pass a variable/parameter to big.NewInt()


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?


Solution

  • The error is because the https://pkg.go.dev/math/big#NewInt function takes an int64 value as the argument and not an int type. Do the required type conversion as

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

    Moreover the computation logic can very simply written 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://go.dev/play/p/A-H-y10OwBb