LightOJ1197 Help Hanzo(欧拉筛+区间素数)

题目链接

Problem 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<2^31, 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, …

题意

在0到2^31次方范围内给出差值不超过100000的两个数a,b,要求两数间质数的数量。

思路

因为2^31次方数字过大,所以无法直接筛素数,需要考虑其他的方法。由于a,b的差值有限,可以考虑利用合理范围内的素数表将[a,b]映射至[0,b-a]区间,再通过放大的方法将其还原至所需区间并标记为非质数,最后遍历对其进行记数。

代码

#include<map>
#include<set>
#include<stack>
#include<queue>
#include<string>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define pb push_back
using namespace std;
//const int mod=998244353;
const int maxn=1e6+5;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
bool vis[maxn],flag[maxn];
ll a,b,cnt,tot,prime[maxn];
void eul(ll n)
{
    
    
	cnt=0;
	vis[1]=true;
	for(ll i=2;i<=n;i++)
	{
    
    
		if(!vis[i])
			prime[++cnt]=i;
		for(ll j=1;j<=cnt&&i*prime[j]<=n;j++)
		{
    
    
			vis[i*prime[j]]=true;
			if(i%prime[j]==0)
				break;
		}
	}
}
int main()
{
    
    
	int t;
	eul(maxn);
	scanf("%d",&t);
	for(int ca=1;ca<=t;ca++)
	{
    
    
		tot=0;
		scanf("%lld%lld",&a,&b);
		if(b<maxn)
		{
    
    
			for(ll i=a;i<=b;i++)
			{
    
    
				if(!vis[i])
					tot++;
			}
		}
		else
		{
    
    
			memset(flag,false,sizeof flag);
			for(ll i=1;i<=cnt;i++)
			{
    
    
				ll tmp=(a+prime[i]-1)/prime[i];//缩小并保证放大后不会导致a漏筛 
				for(ll j=tmp*prime[i];j<=b;j+=prime[i])
				{
    
    
					flag[j-a]=true;
				}//放大至[a,b]区间并标记 
			}
			for(ll i=0;i<=b-a;i++)
			{
    
    
				if(!flag[i])
					tot++;
			}
		}
		printf("Case %d: %lld\n",ca,tot);
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/WTMDNM_/article/details/108759115