http://acm.hust.edu.cn/vjudge/contest/view.action?cid=70017#problem/M
Description
Amakusa, the evil spiritual leader has captured the beautiful princess Nakururu. The reason behind this is he had a little problem with Hanzo Hattori, the best ninja and the love of Nakururu. After hearing the news Hanzo got extremely angry. But he is clever and smart, so, he kept himself cool and made a plan to face Amakusa.
Before reaching Amakusa's castle, Hanzo has to pass some territories. The territories are numbered as a, a+1, a+2, a+3 ... b. But not all the territories are safe for Hanzo because there can be other fighters waiting for him. Actually he is not afraid of them, but as he is facing Amakusa, he has to save his stamina as much as possible.
He calculated that the territories which are primes are safe for him. Now given a and b he needs to know how many territories are safe for him. But he is busy with other plans, so he hired you to solve this small problem!
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a line containing two integers a and b (1 ≤ a ≤ b < 231, b - a ≤ 100000).
Output
For each case, print the case number and the number of safe territories.
Sample Input
3
2 36
3 73
3 11
Sample Output
Case 1: 11
Case 2: 20
Case 3: 4
题目大意:
给出T个实例,T<=200,给出[a,b]区间,问这个区间里面有多少个素数?(1 ≤ a ≤ b < 231, b - a ≤ 100000)
解题思路:
由于a,b的取值范围比较大,无法把这个区间内的所以素数全部筛选出来,但是b-a这个区间比较小,所以可以用区间素数筛选的办法解决这个题目。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
#include <vector>
#include <map>
using namespace std;
#define N 60000
#define INF 0x3f3f3f3f
#define PI acos (-1.0)
#define EPS 1e-8
#define met(a, b) memset (a, b, sizeof (a))
typedef long long LL;
int isprim[N], num[N*10], k = 0;
bool a[N] = {1, 1};
void prim ();//只需要把[1,sqrt(2^31)]之间的素数筛选出来就ok了
int main ()
{
int t, n, a, b, nCase = 1;
scanf ("%d", &t);
prim ();
while (t--)
{
scanf ("%d %d", &a, &b);
n = b - a;//所求区间最大可达下标
met (num, 0);
for (int i=0; isprim[i]*isprim[i]<=b, i<k; i++)
{
int j = 0;
if (a % isprim[i] != 0)//第一个需要筛掉的数(j+a) % isprime[i] == 0
j = isprim[i] - a % isprim[i];
if (a <= isprim[i])//(j+a) / isprime[i] == 1,则(j+a)是素数,要向下推一个
j += isprim[i];
for (; j<=n; j+=isprim[i])
num[j] = 1;
}
int ans = 0;
for (int i=0; i<=n; i++)
if (!num[i]) ans++;//计算素数的数目
if (a == 1) ans--;//对这种情况特殊处理
printf ("Case %d: %d\n", nCase++, ans);
}
return 0;
}
void prim ()
{
for (int i=2; i<N; i++)
{
if (!a[i])
{
isprim[k++] = i;
for (int j=i+i; j<N; j+=i)
a[j] = 1;
}
}
}