快速计算素数程序
Wheel factorization
Wheel factorization是一种生成素数方法。
对于大于30的数,只有30n+1,30n+7,30n+11,30n+13,30n+17,30n+19,30n+23,30n+29才可能是素数,这里n>=1。
#include <stdio.h> #include <math.h> #define NUM_O_PRIMES 2015 long primes1[NUM_O_PRIMES]; void primes() { int base = 30, pc = 0, column[] = {1, 7, 11, 13, 17, 19, 23, 29}; int pp = 0; primes1[pp++] = 2; primes1[pp++] = 3; primes1[pp++] = 5; primes1[pp++] = 7; primes1[pp++] = 11; primes1[pp++] = 13; primes1[pp++] = 17; primes1[pp++] = 19; primes1[pp++] = 23; primes1[pp++] = 29; while(pp < NUM_O_PRIMES) { if(pc == 8) { base += 30; pc = 0; } long p, q; p = base + column[pc++]; q = sqrt(p); int j = 3; while(primes1[j] <= q) { if(p % primes1[j] == 0) break; j++; } if(primes1[j] > q) primes1[pp++] = p; } } int main(void) { primes(); int i; for(i=0; i<NUM_O_PRIMES; i++) { printf("%d:%ld\n", i+1, primes1[i]); } return 0; }