整数n的阶乘指 1*2*3*...*(n-1)*n 的值,在n=171时,计算机一般会出错(“溢出”),本文采用字符串模拟数字乘法运算,使计算10000!成为可能:
Function multi(ByVal X As String, ByVal Y As String) As String 'multi of two huge hexnum(两个大数之积)
Dim result As Variant
Dim xl As Long, yl As Long, temp As Long, i As Long
xl = Len(Trim(X))
yl = Len(Trim(Y))
ReDim result(1 To xl + yl)
For i = 1 To xl
For temp = 1 To yl
result(i + temp) = result(i + temp) + Val(Mid(X, i, 1)) * Val(Mid(Y, temp, 1))
Next
Next
For i = xl + yl To 2 Step -1
temp = result(i) \ 10
result(i) = result(i) Mod 10
result(i - 1) = result(i - 1) + temp
Next
If result(1) = "0" Then result(1) = ""
multi = Join(result, "")
Erase result
End Function
Private Sub Command1_Click() '节约时间,算到1000!
For i = 1 To 9
calcfactorial i * 100
Next
End Sub
Sub calcfactorial(ByVal n As Integer)
Dim a() As String, i As Long, stimer As Double
ReDim a(1 To n)
a(1) = 1
stimer = Timer
For i = 2 To n
a(i) = multi(a(i - 1), i)
Next
Debug.Print n & "! : 用时 "; Timer - stimer & " 秒, 结果 " & Len(a(n)) & " 位"
Debug.Print a(n)
End Sub
100! : 用时 4.67617187496217E-02 秒, 结果 158 位
200! : 用时 .407124999999724 秒, 结果 375 位
300! : 用时 1.00012499999957 秒, 结果 615 位
400! : 用时 1.92199999999957 秒, 结果 869 位
500! : 用时 3.14013671875 秒, 结果 1135 位
600! : 用时 4.68677343750005 秒, 结果 1409 位
700! : 用时 6.64099999999962 秒, 结果 1690 位
800! : 用时 8.9208984375 秒, 结果 1977 位
900! : 用时 11.5000117187501 秒, 结果 2270 位
1000! : 用时 14.5621367187496 秒, 结果 2568 位