Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

math

swift

I am making fuction that calculate 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 untill 20.

I think factorial(21) value bigger than UINT64_MAX.

then How to calculate the 21! (21 factorial) in swift?

like image 757
dialektike Avatar asked Nov 12 '15 07:11

dialektike


People also ask

How do you find 20 factorial?

The Factorial of n is denoted by n! Thus, the factorial of 20 is 2432902008176640000.


1 Answers

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?

like image 142
Han Avatar answered Nov 02 '22 08:11

Han