Sieve of Atkin是一种快速的素数筛选算法,算法比较成熟和简单,http://en.wikipedia.org/wiki/Sieve_of_Atkin中的描述已经非常的细致,作者撰写此文的目的在于,对如何把伪代码转为C代码作一个引导,参考如下的示例。
#include <math.h>
#include <stdio.h>
/* limit ← 1000000 */
#define LIMIT (1000000)
#define FALSE (0)
#define TRUE (~FALSE)
int main(int argc, char* argv[])
{
int sieve_list[LIMIT + 1];
int n, r;
int x, y;
int k, i;
/* is_prime(i) ← false, ∀ i ∈ [5, limit] */
for(n = 5; n <= LIMIT; n++)
sieve_list[n] = FALSE;
/* for (x, y) in [1, √limit] × [1, √limit]: */
for(x = 1; x <= (int)sqrt(LIMIT); x++)
for(y = 1; y <= (int)sqrt(LIMIT); y++)
{
/*
n ← 4x²+y²
if (n ≤ limit) and (n mod 12 = 1 or n mod 12 = 5):
is_prime(n) ← ¬is_prime(n)
*/
n = 4 * x * x + y * y;
if(n <= LIMIT && (n % 12 == 1 || n % 12 == 5))
sieve_list[n] = ~sieve_list[n];
/*
n ← 3x²+y²
if (n ≤ limit) and (n mod 12 = 7):
is_prime(n) ← ¬is_prime(n)
*/
n = 3 * x * x + y * y;
if(n <= LIMIT && n % 12 == 7)
sieve_list[n] = ~sieve_list[n];
/*
n ← 3x²-y²
if (x > y) and (n ≤ limit) and (n mod 12 = 11):
is_prime(n) ← ¬is_prime(n)
*/
n = 3 * x * x - y * y;
if(x > y && n <= LIMIT && n % 12 == 11)
sieve_list[n] = ~sieve_list[n];
}
/*
for n in [5, √limit]:
if is_prime(n):
is_prime(k) ← false, k ∈ {n², 2n², 3n², ..., limit}
*/
for(n = 5; n <= sqrt(LIMIT); n++)
if(sieve_list[n] == TRUE)
{
i = 1;
k = i++ * n * n;
while(k <= LIMIT)
{
sieve_list[k] = FALSE;
k = i++ * n * n;
}
}
/* print 2, 3 */
printf("2\n3\n");
/*
for n in [5, limit]:
if is_prime(n): print n
*/
for(n = 5; n <= LIMIT; n++)
if(sieve_list[n] == TRUE)
printf("%d\n", n);
return 0;
}