calculate the inverse of the factorial of a number in swift

To calculate the inverse of the factorial of a number, we need to first calculate the factorial of that number, and then take the reciprocal of the result. Here's a function in Swift that does just that:

main.swift
func inverseFactorial(_ n: Int) -> Double? {
    guard n > 0 else { return nil } // factorials are undefined for negative numbers
    var result = 1
    for i in 2...n {
        result *= i
    }
    return 1.0 / Double(result)
}
230 chars
9 lines

This function takes an input n and returns an optional Double value, which is the inverse of the factorial of n. If the input n is less than or equal to zero, the function returns nil, because the factorial is undefined for non-positive numbers.

The function uses a for loop to calculate the factorial of n. It initializes a variable result to 1, and then multiplies it by each integer from 2 to n. Finally, it returns the reciprocal of the result as a Double value.

gistlibby LogSnag