运行时间和下式成正比:N+N/2+N/3+N/7+N/11+……
#include <cstdio> #include <cstdlib> using namespace std; int main(int argc, char* argv[]) { int n; if (argc != 2) { printf("usage:bin n "); exit(0); } n = atoi(argv[1]); int i; int* arr = (int *)malloc(sizeof(int)*(n+1)); for (i = 0; i <= n; i++) arr[i] = 1; int j; for (i = 2; i <= n; i++) { if (arr[i]!=0) for (j = i; j*i <= n;j++) arr[i*j] = 0; } for (i = 2; i <= n;i++) if (arr[i]) printf("%d ",i); printf(" "); return 0; }
指定参数为100后,得到100以内的质数,如下: