How to compute the factorial of a number greater than 20 in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/big"
)

/*
    This program computes the factorial of numbers greater than 20.
    Go's math/big package provides big.Int, an arbitrary‑precision
    integer type that can represent extremely large numbers safely.
*/

/*
    Compute factorial using big.Int.
    The algorithm multiplies numbers from 2 to n.
    big.Int handles overflow internally and grows as needed.
*/
func factorialBig(n int64) *big.Int {
    result := big.NewInt(1)

    for i := int64(2); i <= n; i++ {
        result.Mul(result, big.NewInt(i))
    }

    return result
}

/*
    Main entry point: read input, compute factorial, print result.
*/
func main() {
    var n int64

    fmt.Print("Enter a number greater than 20: ")
    fmt.Scan(&n)

    result := factorialBig(n)

    fmt.Printf("\nFactorial of %d is:\n\n", n)
    fmt.Println(result.String())
}


/*
run:

Enter a number greater than 20: 25
Factorial of 25 is:

15511210043330985984000000

*/

 



answered Sep 14 by avibootz

Related questions

...