一般筛法:
1 void prime() { 2 memset(vis, true, sizeof(vis)); 3 vis[0] = vis[1] = false; 4 for (int i = 2; i < maxn; i++) { 5 for (int j = 2; i * j < maxn; j++) { 6 vis[i * j] = false; 7 } 8 } 9 }
快速线性筛法:
1 int prime[N] = {0}; 2 bool isNotPrime[N] = {1, 1}; 3 int num_prime = 0; 4 5 void quick_prime() 6 { 7 for(int i = 2 ; i < N ; i ++) 8 { 9 if(! isNotPrime[i]) //i是合数的话,i = p1 * p2 * p3 * ··· 10 prime[num_prime ++] = i; 11 for(int j = 0 ; j < num_prime && i * prime[j] < N ; j ++) 12 { 13 isNotPrime[i * prime[j]] = 1; 14 if( !(i % prime[j] ) ) // 当p1 == prime[j]时,筛除终止。筛出不大于p1的素数*i 15 break; 16 } 17 } 18 }