lightoj1197

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

Note

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 之间素数的个数

思路:

先打表 [2 , 1e6]之间的素数

当b < 1e6 时 , 直接循环找答案

当b > 1e6 时 ,筛 [a , b]的素数

再用映射的方法存下

代码:
 

#include<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
using namespace std;
const int maxn = 1e6+5;
//
bool vis[maxn] , visab[maxn];
int prime[maxn] , cnt = 0;
void is_prime()//到 maxn 的素数个数 
{
	memset(vis , 0 , sizeof(vis));
	vis[1] = 1;
	for(int i = 2 ; i < maxn ; i++)
	{
		if(!vis[i])
		{
			prime[cnt++] = i;
			for(int j = i+i ; j < maxn ; j+=i)
			{
				vis[j] = 1;
			}
		}
	}
}
int main()
{
	int t;
	cin >> t;
	is_prime();
	for(int k = 1 ; k <= t ; k++)
	{
		ll a , b;
		scanf("%lld %lld" , &a , &b);
		int count = 0;//记录 a 到 b 素数个数 
		if(b <= maxn-1)
		{
			for(ll i = a ; i <= b ; i++)
			{
				if(!vis[i])
				count++;
			}
		}
		else//cnt 素数个数 
		{
			memset(visab , 0 , sizeof(visab));
			for(int i = 0 ; i < cnt ; i++)//maxn以内素数 
			{
				ll p = a/prime[i];
				if(a % prime[i] != 0) 
			//	if(p*prime[i] < a)
				p++;
				for(ll j = p *prime[i] ; j <= b ; j+=prime[i])
				{
					visab[j-a] = 1;//j-a是为了能存下 
				}
			}
			for(ll i = a ; i <= b ; i++)
			{
				if(!visab[i-a])
				{
					count++;
				}
			 } 
		}
		printf("Case %d: %d\n" , k , count);
	 } 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/88697983