我试图找到一个数字x的最大质数除数。当x小于10亿时,我的代码可以工作,但是当它大于10亿时,它会产生溢出错误并且调试会突出显示包含Mod的行。
Sub Largest_Divisor()
Dim x As Double
Dim Q As Integer
Q = 0
Dim L() As Double
x = 999999999#
Dim i As Double
For i = 775145 To 3 Step -2
If x Mod i = 0 Then
If IsPrime(i) Then
ReDim Preserve L(Q) As Double
L(Q) = i
Q = Q + 1
End If
End If
Next i
MsgBox (Application.Max(L))
End Sub
我怀疑它是x
大于约20亿,2,147,483,648
准确,你有麻烦。
这是因为根据mod
的文档,最多返回一个long
,其值从-2,147,483,648
到2,147,483,647
的值为32位有符号值。它没有在帮助文档中明确说明,但mod
的论点也可能被强制用于long
。
一个好的方法是使用这个功能:
Function Modulus(int1 As Double, int2 As Double) As Double
' This function will return int1 Mod int2. It is useful when |int1| exceeds
' 2,147,483,647 as the VBA Mod function will then break.
'
Dim myInt As Integer
myInt = Int(int1 / int2)
Modulus = int1 - (myInt * int2)
End Function