刚开始,我用正常的素数筛:
#include<bits/stdc++.h>
using namespace std;
bool isprime (int s) {
for (int i = 2; i*i <= s; i++) {
if (s % i == 0) { //判断有没有除1和他本身以外的因数
return 0;
}
}
return 1;
}
int main () {
int cnt = 0;
int n;
cin >> n;
for (int i = 2; i <= n; i++) {
if (isprime(i) == 1) {
cnt++;
}
}
cout << cnt << endl;
return 0;
}
然后,60pts,TLE了4个。
于是,我换成了埃氏筛:
#include<bits/stdc++.h>
using namespace std;
bool a[10000005];
void isprime (int s) {
for (int i = 2; i <= s; i++) {
if (a[i] == 0) {
for (int j = i*i; j <= s; j += i) {
a[j] = 1;
}
}
}
return;
}
int main () {
int cnt = 0;
int n;
cin >> n;
isprime(n);
for (int i = 2; i <= n; i++) {
if (a[i] == 0) {
cnt++;
}
}
cout << cnt << endl;
return 0;
}
结果,直接变成9个RE了。
问题来了:
为什么会这样?