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

后端 未结 6 1047
悲&欢浪女
悲&欢浪女 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:14
    func factorial(_ n: Int) -> Double {
      return (1...n).map(Double.init).reduce(1.0, *)
    }
    
    0 讨论(0)
  • 2020-12-03 12:15

    Using recursion to solve this problem:

        func factorial(_ n: UInt) -> UInt {
            return n < 2 ? 1 : n*factorial(n - 1)
        }
    
    0 讨论(0)
  • 2020-12-03 12:24

    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?

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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))
    }
    
    0 讨论(0)
  • 2020-12-03 12:35

    Here's a function that accepts any type that conforms to the Numeric protocol, which are all builtin number types.

    func factorial<N: Numeric>(_ x: N) -> N {
        x == 0 ? 1 : x * factorial(x - 1)
    }
    
    0 讨论(0)
提交回复
热议问题