溢出异常? [英] 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
通常会导致溢出.仅当我从4之类的小内容开始时才起作用.
It usually results in an overflow. It only works if I start with something small like 4.
我必须使用30-60之类的起始号码.
I have to work with starting numbers such as 30-60.
有什么想法吗?我认为将值类型更改为LONG可以避免此问题.
Any ideas? I thought changing the value type to LONG would prevent this problem.
这是VB.net,仅供参考.
This is VB.net just for reference.
推荐答案
框架变得非常大,非常快. Long
中可容纳的最大数字约为9×10 ^ 18.阶乘(30)约为2.7×10 ^ 32.
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.
如果您未使用.Net 4,则需要查找并下载BigInteger库,例如 intx .
If you're not using .Net 4, you'll need to find and download a BigInteger library, for example intx.
这篇关于溢出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!