Search code examples
scalafactorial

Int Overflow w/ Factorial


Given:

def factorial(n: Int): Int = {
    if(n <= 0) 1
    else       n * factorial(n - 1)
}

Also, since I chose an Int, the following, I believe, overflow behavior is possible:

scala> factorial(35)
res3: Int = 0

What's a simple example of int multiplication leading to an overflow equal to 0?


Solution

  • What's a simple example of int multiplication leading to an overflow equal to 0?

    scala> -2147483648 * 2
    res4: Int = 0
    

    Where :

    Int.MaxValue + 1 = -2147483648
    

    For factorial(35) it definitely overflowed more than once on it's way there.