Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
XML RSS Feed
 
 
 
 
 
 
 
 
Old Pages
 
Old Index
Site Map
What's New
 
Books
How To
Tips & Tricks
Tutorials
Stories
Performance
Essays
Links
Q & A
New in VB6
Free Stuff
Pictures
 
 
 
TitleList prime numbers
Keywordsprime, factor
CategoriesAlgorithms, Puzzles and Games
 
Build an array of Booleans, one for each value from 1 to max (the largest number you want to consider). For i = 1 to max\2, if i is still marked as prime then cross out multiples of i.
 
Private Sub cmdFindPrimes_Click()
Dim is_prime() As Boolean
Dim max_number As Long
Dim i As Long
Dim j As Long
Dim txt As String

    Screen.MousePointer = vbHourglass
    
    ' Create the array.
    max_number = CLng(txtMaxNumber.Text)
    ReDim is_prime(2 To max_number)
    For i = 2 To max_number
        is_prime(i) = True
    Next i

    For i = 2 To max_number \ 2
        If is_prime(i) Then
            ' Cross out all numbers that are
            ' multiples of this one.
            For j = 2 To max_number \ i
                is_prime(j * i) = False
            Next j
        End If
    Next i
    
    ' Display the primes.
    j = 0
    For i = 2 To max_number
        If is_prime(i) Then
            txt = txt & Format$(i, "@@@@@@@")
            j = j + 1
            If (j Mod 5) = 0 Then txt = txt & vbCrLf
        End If
    Next i
    txtPrimes.Text = txt

    Screen.MousePointer = vbDefault
End Sub
 
 
Copyright © 1997-2003 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated