整数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 位