I am trying to code the Sieve of Atkin algorithm for finding prime numbers. I haven't been able to find any existing VB code, so I have based my algorithm on this C++ implementation.
My function is not correctly marking all the primes. For example, when I try to find the prime numbers to 100 the function only returns:
To my eye the code looks correct (in relation to the C++ it is based on), and I have tried to cross check it against the pseudocode in the Wikipedia Article (above), and again to me it looks correct. My math isn't very strong, so I am not sure if I am misinterpreting some of the symbols.
Some new sets of eyes and any advice would be appreciated.
My function is not correctly marking all the primes. For example, when I try to find the prime numbers to 100 the function only returns:
VB.NET:
2 3 5 7 13 19 29 53 67 85
To my eye the code looks correct (in relation to the C++ it is based on), and I have tried to cross check it against the pseudocode in the Wikipedia Article (above), and again to me it looks correct. My math isn't very strong, so I am not sure if I am misinterpreting some of the symbols.
Some new sets of eyes and any advice would be appreciated.
VB.NET:
Private Function AtkinSieve(ByVal limit As Integer) As Integer()
Dim root As Integer = Math.Ceiling(Math.Sqrt(limit))
Dim sieve(limit) As Boolean
Dim primes(1) As Integer
Dim insert As Integer = 2
primes(0) = 2
primes(1) = 3
For z = 0 To limit
sieve(z) = False
Next
' Main part of Sieve of Atkin
Dim x As Integer = 1
Dim y As Integer = 1
While x <= root
While y <= root
Dim n As Integer = (4 * (x * x)) + (y * y)
If (n <= limit And (n Mod 12 = 1 Or n Mod 12 = 5)) Then sieve(n) ^= True
n = (3 * (x * x)) + (y * y)
If (n <= limit And (n Mod 12 = 7)) Then sieve(n) ^= True
n = (3 * (x * x)) - (y * y)
If (x > y And n <= limit And n Mod 12 = 11) Then sieve(n) ^= True
y += 1
End While
x += 1
End While
' Mark all multiples of squares as non-prime
Dim r As Integer = 5
Dim i As Integer = 0
While r <= root
If sieve(r) Then
i = (r ^ 2)
While i < limit
sieve(i) = False
i += (r ^ 2)
End While
End If
r += 1
End While
' Add into the prime array
Dim a As Integer = 5
While a < limit
If sieve(a) Then
Redim Preserve primes(insert)
primes(insert) = a
insert += 1
End If
a += 1
End While
Return primes
End Function