user6800688 - 6 months ago 21

Scala Question

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(93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000) {
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("93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000")) {
factorial.recursive_factorial(100)
}
```