user6800688 user6800688 - 2 months ago 6
Scala Question

Why can't I compute the factorial of 100 in scala?

I'm unit testing and I can't compute the factorial of 100. I read that using BigInt would help, but I'm not sure what I'm doing wrong, because it still doesn't work.

Here is my function.

package Factorial{
class factorial
{
def recursive_factorial(number:BigInt) : BigInt =
{
if (number == 0)
return 1
number * recursive_factorial (number - 1)
}
}
}


If I call the function with recursive_factorial(100).. I get an error that the number is too large for an int

Answer

The code you posted works fine. The problem with the code you use to test your code (which you posted in a comment to another answer):

assertResult(93326215443944152681699238856266700490715968264‌​38162146859296389521‌​75999932299156089414‌​63976156518286253697‌​92082722375825118521‌​09168640000000000000‌​00000000000) {
    factorial.recursive_factorial(100)
}

The problem is that integer literals have type Int and the number 93326... is obviously too large to fit into an int, so you can't use an integer literal to represent it.

One way to create a BigInt of a large number is to write it as a string and convert that to a BigInt. So this will work fine:

assertResult(BigInt("93326215443944152681699238856266700490715968264‌​38162146859296389521‌​75999932299156089414‌​63976156518286253697‌​92082722375825118521‌​09168640000000000000‌​00000000000")) {
    factorial.recursive_factorial(100)
}