I'm working on writing a basic recursive function in Swift. The function is calculating the factorial of the input perfectly, but I run into an overflow error when I try to calculate the factorial of a number over 20.
I have read through the apple docs on error handling https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html, but I haven't been able to successfully integrate the guard keyword into the recursive function.
func factorial(number: Int) -> Int {
if (number <= 1){
return 1
} else {
return factorial(number: number - 1) * number
}
}
factorial(number: 0) *1*
factorial(number: 1) *1*
factorial(number: 5) *120*
factorial(number: 20) *2432902008176640000*
factorial(number: 21) *error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=...*
Any suggestions would be great!