I implemented the Sieve of Atkin in C++ to return a Vector of type bool, but it does not tag some Primes.
// Example program
#include <iostream>
#include <vector>
std::vector<bool> listPrimes(int limit){
std::vector<bool> primes(limit);
primes[2] = primes[3] = true;
for(int i=1; i*i < limit; ++i){
for(int j=1; j*j < limit; ++j){
int n = (4*i*i) + (j*j);
if (n <= limit && (n % 12 == 0 || n % 12 == 5 ))
primes[n] = !primes[n];
n = (3*i*i) + (j*j);
if (n <= limit && n % 12 == 7 )
primes[n] = !primes[n];
n = (3*i*i) - (j*j);
if ( i > j && n <= limit && n % 12 == 11 )
primes[n] = !primes[n];
}
}
for(int i=5; i*i < limit; ++i ){
if(primes[i])
for(int j=i*i; j < limit; j+=i*i)
primes[i] = false;
}
return primes;
}
int main()
{
std::vector<bool> primes = listPrimes(100);
for(int i=0; i < 100; ++i)
if(primes[i])
std::cout << i << ", ";
return 0;
}
Here is the output of the Given Code. 2, 3, 11, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 67, 71, 72, 79, 83, 89,
What am I doing wrong ?
You have 3 mistakes (typos) in your code:
Replace
n <= limitwithn < limiteverywhere.Replace
n % 12 == 0withn % 12 == 1.Replace
primes[i] = false;withprimes[j] = false;After fixing all 3 mistakes above your algorithm works totally correctly! Fixed code is at the end of my post, copy-paste
listPrimes()function only from it.In order to check correctness of your algorithm, I wrote a special (quite advanced) C++ program located at the end of my post.
I compare your results with alternative primes computation algorithm Sieve of Eratosthenes that I implemented in a separate function.
More than that I check not only one
limitvalue but ALL limit values till 2^14, and partially (with some step) limit values till 2^27. So I test really a lot of examples!And all of them (test examples) are passing after those 3 fixes above. So I can assume then your algorithm is correct.
As I understand your code implements alternative way of computing Atkin. The one Atkin Wiki provides totally different way of computation. Instead of
n % 12it uses set of reminders modulus 60 (n % 60).But surprisingly your version works too! Probably it is a simplified (more slow) version of Atkin.
My code outputs to console progress of checking
limittill some power of 2 and show if all limits are checked or with some step. See example of console output located after the code below.Try it online!
Console output: