Search code examples
swiftmath

How to calculate the 21! (21 factorial) in Swift?


I am making fuction that calculates factorial in Swift. Like this:

func factorial(factorialNumber: UInt64) -> UInt64 {
    if factorialNumber == 0 {
        return 1
    } else {
        return factorialNumber * factorial(factorialNumber - 1)
    }
}

let x = factorial(20)

This fuction can calculate until 20!.

I think factorial(21) is bigger than UINT64_MAX.

How to accurately calculate 21! (21 factorial) in Swift?


Solution

  • Unsigned 64 bit integer has a maximum value of 18,446,744,073,709,551,615. While 21! = 51,090,942,171,709,440,000. For this kind of case, you need a Big Integer type. I found a question about Big Integer in Swift. There's a library for Big Integer in that link.

    BigInteger equivalent in Swift?