# 质数筛选--快速筛选出小于等于N的质数

## Eratosthenes筛法（O(nlog^logn) )

1. 维护一个数组vector<bool> prime(n + 1, true)既让数组中的所有数都为真，表明它是质数。
2. 对于每一个质数，删除它的倍数，因为质数的倍数一定是合数。让后将数组中对应的数改为false，这样就可以避免遍历他。

int findPrime(int n) {
vector<bool> prime(n + 1, true);
int res=0;
for (int i = 2; i <= n; i++) {
if (prime[i]) {        //判断其是否是素数
for (int j = 2; j*i <= n; j++)  //删除所有该素数的倍数
prime[j*i] = false;
res++;
}
}
return res;
}

## Eular质数筛法

int findPrime1(int n) {
vector<bool> prime(n + 1, true);
vector<int> primeList(n+1); int primeCount = 0;
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeCount++;
primeList[primeCount] = i;
}
for (int j = 1; j <= primeCount; j++) {
if (i*primeList[j] > n) break;
prime[i*primeList[j]] = false;
if (i%primeList[j] == 0) break;
}
}
return primeCount;
}

int main() {
clock_t start = clock();
cout << findPrime1(5000000) << endl;
clock_t finish = clock();
cout<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;        //11.854s
clock_t start2 = clock();
cout << findPrime1(5000000) << endl;
clock_t finish2 = clock();
cout << (double)(finish2-start2) / CLOCKS_PER_SEC << endl;     //11.81s
}

07-10 3141

06-14 78

11-01 3391

11-19 1457

08-07 556

07-22 1285

03-26 520

03-17 170

02-29 311

03-03 1.3万