Search code examples
vb.netoverflowfactorial

Overflow exception?


I have the following code for finding factorials:

Private Shared Function Factorial(ByVal Number As Long) As Long
        If Number = 0 Then
            Return 1
        Else
            Return Number * Factorial(Number - 1)
        End If
End Function

It usually results in an overflow. It only works if I start with something small like 4.

I have to work with starting numbers such as 30-60.

Any ideas? I thought changing the value type to LONG would prevent this problem.

This is VB.net just for reference.


Solution

  • Factorials get very large, very quickly. The largest number that will fit in a Long is about 9×10^18. Factorial(30) is about 2.7×10^32.

    If you're using .Net 4 there is a built-in BigInteger class that you can use which will hold arbitrarily large numbers.

    If you're not using .Net 4, you'll need to find and download a BigInteger library, for example intx.