对于每个不超过n的非负整数p,删除2p,3p,4p,处理完所有的数之后,没被删除的就是素数。
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int * a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
for (int i = 2; i < sqrt(double(n)); i++)
for (int j = i + 1; j < n; j++)
if (a[j] != 0 && a[j] % i == 0)
a[j] = 0;
for (int i = 2; i < n; i++)
if (a[i] != 0)
cout << a[i] << " ";
return 0;
}