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

后端 未结 6 1057
悲&欢浪女
悲&欢浪女 2020-12-03 11:42

I am making fuction that calculate factorial in swift. like this

func factorial(factorialNumber: UInt64) -> UInt64 {
    if factorialNumber == 0 {
                


        
6条回答
  •  难免孤独
    2020-12-03 12:28

    If you are willing to give up precision you can use a Double to roughly calculate factorials up to 170:

    func factorial(_ n: Int) -> Double {
        if n == 0 {
            return 1
        }
        var a: Double = 1
        for i in 1...n {
            a *= Double(i)
        }
        return a
    }
    

    If not, use a big integer library.

提交回复
热议问题