Search code examples
excelmodulovba

Overflow error with Mod in VBA when value is in the billions or greater


I am trying to find the largest prime divisor of a number x. When x is smaller than 1billion my code works but when it is greater than 1billion it gives an overflow error and debugging highlights the line with Mod in it.

 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

Solution

  • I suspect it is when x is larger than about 2 billion, 2,147,483,648 to be precise, that you have trouble.

    That is because as per the documentation of mod, at most a long is returned, which ranges in value from -2,147,483,648 to 2,147,483,647 as a 32-bit signed value. It is not explicitly stated in the help documentation, but the arguments of mod are probably coerced to long as well.