Robson » Code » VB6 » Prime Number Finder

 
' Prime Number Finder


' Speed tests:
' 100,000 = 0.05 seconds
' 500,000 = 0.39 seconds
' 1,000,000 = 0.92 seconds
' 5,000,000 = 7.78 seconds
' 10,000,000 = 19.77 seconds

Option Explicit

' find all prime numbers up to this
Private Const MAX_PRIME As Long = 1000000
' and put them into this array
Dim lngPrimes() As Long

Public Sub GeneratePrimeNumbers()
Dim A As Long, B As Long, C As Long
Dim blnNotPrime As Boolean
Dim lngSqr As Long
ReDim lngPrimes(0)
lngPrimes(0) = 2
For A = 3 To MAX_PRIME Step 2
blnNotPrime = False
lngSqr = Sqr(A)
For B = 1 To C
If A Mod lngPrimes(B) = 0 Then
blnNotPrime = True
Exit For
End If
If lngPrimes(B) > lngSqr Then
Exit For
End If
Next
If Not blnNotPrime Then
C = C + 1
If UBound(lngPrimes) < C Then
ReDim Preserve lngPrimes(C + 10)
End If
lngPrimes(C) = A
End If
Next
ReDim Preserve lngPrimes(C)
End Sub

 
© 2004-17 robson | cc unless stated