- 题目大意
在一个区间中去寻找素数的个数。
- 解题思路
由于a,b的取值范围比较大,无法把这个区间内的所以素数全部筛选出来,但是b-a这个区间比较小,所以可以用区间素数筛选的办法解决这个题目。
- 代码
#include<iostream> #include<cmath> #include<cstring> using namespace std; const int MAX = 1e6 + 5; bool vis[MAX],vis2[MAX]; int cnt = 0; int p[MAX]; void num() { memset(vis, 0, sizeof(vis)); vis[1] = 1; for (int i = 2; i <MAX; i++) { if (!vis[i]) { p[cnt++] = i; for (long long j = i*2; j <= MAX; j += i) { vis[j] = 1; } } } } int main() { long long n, a, b; cin >> n; num(); for (long long i = 1; i <= n; i++) { long long sum = 0; cin >> a >> b; if (b <= MAX - 1) { for (long long i = a; i <= b; i++) { if (!vis[i]) sum++; } } else { memset(vis2, 0, sizeof(vis2)); for (int i = 0; i<cnt&&p[i] <= b; i++) { long long k = a / p[i]; if (k*p[i]<a) k++; for (long long j = k * p[i]; j <= b; j += p[i]) { vis2[j - a] = 1; } } for (long long i = a; i <= b; i++) { if (!vis2[i - a]) sum++; } } cout << "Case " << i << ": "; cout << sum << endl; } return 0; }