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 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).
For each case, print the case number and the number of safe territories.
3
2 36
3 73
3 11
Case 1: 11
Case 2: 20
Case 3: 4
A number is said to be prime if it is divisible by exactly two different integers. So, first few primes are 2, 3, 5, 7, 11, 13, 17, ...
就是给你一个区间[a,b]让你求这个区间素数的个数
但a、b的值太大没法直接进行素数筛选(没法开那么大的数组),我们可以将a当做0,将b当做b-a
这样求[a,b]之间就变成了求[0, 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了
{
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;
}
}
}
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;
}