Factorials in Swift

I need a good factorial function. The one I wrote here works completely except when n gets too large. This is for a calculator app, and I can return 0/0 for values ​​that cannot be factorized because I have an error checker that will declare that this is not possible. However, executing a function on a very large number causes the application to crash. I cannot use the range operator because my types are doubled.

func factorial(n: Double) -> Double {
    if n >= 0 {
        return n == 0 ? 1 : n * self.factorial(n - 1)
    } else {
        return 0 / 0
    }
}

      

What's the best way to do this?

+3


source to share


2 answers


As others have said, you can use libraries that support large numbers, or just don't allow too large values.

Please note that if you want to handle very large values, you may need to use a loop rather than a recursive algorithm, because recursion can cause Stack Overflow . Yes, that's right, SO "eponymous crash".

To prevent numbers that are too large, print the largest number that won't work, and enter and reject numbers larger than that.



You can determine the number that resets it by going in the opposite direction and logging the count and result every 10 steps:

1 * 2 * 3 * 4 * 5 * 6 ...

If it fails, go back to the previous largest recorded value, start at that by connecting the previously recorded factor result and step 1 at a time until you crash. Then allow n to only be 1 less than your value.

+5


source


Here is a simple non-recursive function in Swift - ~ `~~ - ^ β†’

public func factorial(_ N: Double) -> Double {
    var mult = N
    var retVal: Double = 1.0
    while mult > 0.0 {
        retVal *= mult
        mult -= 1.0
    }
    return retVal   
}

      



Caveat: this function only works for doubles> = 0.0 and zero mantissa

0


source







All Articles