0

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!

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 2
    `21! = 51090942171709440000` is too large to be stored in an `Int`. Compare http://stackoverflow.com/questions/25666008/generic-custom-operator-functions-a-curious-case-of-a-bad-instruction or http://stackoverflow.com/questions/30992191/factorials-in-swift. – Martin R Sep 06 '16 at 21:51
  • Kyle, if you have a new question - even if it is *based* on this one - then ask a new question. Do not change the meaning of this existing one. Thanks. – Eric Aya Sep 12 '16 at 18:32

0 Answers0