主要看程序:
空间 O (n) 时间 O (n) 常数大
10000000 跑了 0.858 秒 可以接受
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100000000;
int n, tot, f[N], prime[N];
void shaiprime(int n) {
for(int i = 2; i <= n; i++) {
if(!f[i]) prime[++tot] = i;
for(int j = 1; j <= tot && i*prime[j] <= n; j++) {
f[i*prime[j]] = 1;
if(!i%prime[j]) break;
}
}
}
int main() {
freopen("shaiprime.in", "r", stdin);
freopen("shaiprime.out", "w", stdout);
scanf("%d\n", &n);
shaiprime(n);
printf("%d\n", tot);
fclose(stdin);
fclose(stdout);
return 0;
}