Light OJ 1197 1197 - Help Hanzo(大区间素数筛选)

来源:互联网 发布:公众号助手mac 编辑:程序博客网 时间:2024/05/17 05:04

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

Output for Sample Input

3

2 36

3 73

3 11

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, ...


由于区间大小达到了2^31的规模,普通的方法无论时间空间达不到。

考虑到b-a<=1e5,我们可以将[a,b]区间是不是素数标记为vis[b-a],空间开销

可以解决。时间上我们可以枚举素数筛选。注意1这种情况。

#include<algorithm>#include<vector>#include<string>#include<iostream>#include<queue>#include<cmath>#include<map>#include<stack>#include<bitset>using namespace std;#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )#define CLEAR( a , x ) memset ( a , x , sizeof a )typedef long long LL;typedef pair<int,int>pil;const int mod = 1000000007;const int INF=0x3f3f3f3f;const int maxn=1e6+5;bool vis[maxn+10];int prim[maxn/10];bool tt[maxn];int cnt=0;void init(){    for(int i=2;i*i<=maxn;i++)        if(!vis[i])        for(int j=i*i;j<=maxn;j+=i)  vis[j]=1;    for(int i=2;i<=maxn;i++)        if(!vis[i])  prim[cnt++]=i;}int main(){    init();    LL t,a,b;    cin>>t;int cas=1;    while(t--)    {        cin>>a>>b;CLEAR(tt,0);        for(int i=0;i<cnt&&(LL)prim[i]*prim[i]<=b;i++)        {             LL st=max(a/prim[i]*prim[i],(LL)prim[i]*prim[i]);             for(LL j=st;j<=b;j+=prim[i])  if(j>=a)  tt[j-a]=1;        }        int ans=0;        for(int i=0;i<=b-a;i++)  if(!tt[i])  ans++;        if(a==1)  ans--;        printf("Case %d: %d\n",cas++,ans);    }    return 0;}



0 0
原创粉丝点击