Eratosthenes筛法
思想: 对于不超过n的每个非负整数p,删除2p,3p,4p,…,当处理完所有数后,还没有被删除的数就是素数.
const int MAXSIZE = 1e8 + 7;
int prime[MAXSIZE] = { 0 };
int main()
{
int n = MAXSIZE;
for (int i = 2; i <= n; ++i) {
if(prime[i]) continue;
for (int j = i * 2; j <= n; j += i) {
prime[j] = 1;
}
}
cout << "1 - " << MAXSIZE << ",所有素数为:" << endl;
for (int i = 2; i <= n; ++i) {
if (!prime[i]) cout << i << endl;
}
return 0;
}
优化
const int MAXSIZE = 1e8 + 7;
int prime[MAXSIZE] = { 0 };
int main()
{
int n = MAXSIZE,m = sqrt(MAXSIZE) + 0.5;
for (int i = 2; i <= m; ++i) {
if(prime[i]) continue;
for (int j = i * i; j <= n; j += i) {
prime[j] = 1;
}
}
cout << "1 - " << MAXSIZE << ",所有素数为:" << endl;
for (int i = 2; i <= n; ++i) {
if (!prime[i]) cout << i << endl;
}
return 0;
}