问题
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.
回答1:
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.
回答2:
You get the overflow exception only with integer and long types. To avoid that, you can use System.Double or System.Numerics.BigInteger (or BigDecimal I think).
For example, if you run 3 different versions of the factorial: 1 with long, 1 with double and 1 with biginteger as follow with a range of values of 5 to 50 by 5:
'Long Factorial
Public Function FactorialInt64(ByVal n As Integer) As Int64
If n = 1 Then
Return 1
Else
Return n * FactorialInt64(n - 1)
End If
End Function
' Double Factorial
Public Function FactorialDouble(ByVal n As Integer) As Double
If n = 1 Then
Return 1
Else
Return n * FactorialDouble(n - 1)
End If
End Function
' BigInteger Factorial
Public Function FactorialBigInteger(ByVal n As Integer) As BigInteger
If n = 1 Then
Return 1
Else
Return n * FactorialBigInteger(n - 1)
End If
End Function
You will get a result like this:

You can find the complete source code in my blog post: Factorial and Fibonacci in VB.NET
回答3:
There is a big int Library for .NET that will solve your problem. It can manipulate very large number (limited only by your system memory).
Here is the link: http://www.emilstefanov.net/Projects/GnuMpDotNet/
来源:https://stackoverflow.com/questions/5483940/overflow-exception