One of the easiest ways to calculate prime numbers
is to use the Sieve of Eratosthenes. The algorithm works by multiplying
numbers in a list to exclude them from being prime. Prime numbers by definition
are numbers greater than one which are only divisible by themselves and
one. Two is the only even prime number, so we will only keep track
of odd numbers starting with three.
3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, etc.
Take the square of the first number (three) and begin there incrementing by three times two:
3, 5, 7, 9,
11, 13, 15, 17, 19, 21,
23, 25, 27, 29, 31, 33,
35, 37, 39, 41, etc.
Take the next number, square it and increment:
3, 5, 7, 9,
11, 13, 15, 17, 19, 21,
23, 25, 27,
29, 31, 33, 35,
37, 39, 41, etc.
Continue on until reaching the square root of the
maximum number. For this example we'll find the primes from two to
five million. In keeping track of the primes use a byte array which
is initially all zeros. Marking each non-prime with a one.
The Visual Basic code looks like this:
Const MAX = 5000000
Dim i As Long
Dim j As Long
Dim lSqrt As Long
Dim lSquare As Long
Dim b(1 To MAX \ 2) As Byte
lSqrt = 2236 'Sqr(MAX)
For i = 3 To
lSqrt Step 2
If b(i\2) = 0 Then
lSquare = i * i
For
j = lSquare To MAX Step
i * 2
b(j \ 2) = 1
Next
j
End If
Next i
VB does this rather quickly (about 300ms on my p233mmx). The most time consuming part of the whole process is converting the long numbers into ascii. VB uses the CStr function which is relatively slow. The whole operation, including writing to file, takes about four seconds. By cheating a bit (no ascii conversion) and using a memory mapped file, the time can be trimmed down to about two seconds. Or we can use ASM (Assembly) and calculate/write to file (IN ASCII!) in one half second.