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

后端 未结 6 1056
悲&欢浪女
悲&欢浪女 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:30

    Did you think about using a double perhaps? Or NSDecimalNumber?

    Also calling the same function recursively is really bad performance wise.

    How about using a loop:

    let value = number.intValue - 1
    
    var product = NSDecimalNumber(value: number.intValue)
    
    for i in (1...value).reversed() {
        product = product.multiplying(by: NSDecimalNumber(value: i))
    }
    

提交回复
热议问题