LightOJ - 1197 Help Hanzo筛素数

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的素数有多少个。如果把所有的素数都筛出来的话内存会超,时间也会超。所以把前面的素数筛出来之后,再用素数去把他的倍数筛掉,用一个大小为b-a的数组标记。

#include<stack>
#include<queue>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<map>
#include<iostream>
#include<string.h>
#include<algorithm>
#define maxn 1000005
#define maxm 10000005
#define MAXN 100005
#define MAXM 10005
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
bool vis[maxn+10];
bool vis1[maxn];
ll tot;
ll p[maxn];
void get_prime(){
     tot=0;
    mem(vis,true);
    for(ll i=2;i<=maxn;i++){
        if(vis[i]){
            p[tot++]=i;
            for(ll j=i*i;j<=maxn;j+=i)vis[j]=false;
        }
    }
}
int main(){
    get_prime();
    int t,test=0;
    scanf("%d",&t);
    while(t--){
        ll a,b;scanf("%lld%lld",&a,&b);
        ll ans=0;mem(vis1,false);
        for(int i=0;i<tot&&p[i]*p[i]<=b;i++){
            ll x=a/p[i]*p[i];if(x<=p[i])x=p[i]*2;
            for(ll j=x;j<=b;j+=p[i])if(j>=a)vis1[j-a]=true;
        }
        for(int i=0;i<=b-a;i++)if(!vis1[i]){ans++;}
        if(a==1)ans-=1;
        printf("Case %d: %lld\n",++test,ans);
    }
}


posted @ 2018-05-16 09:57  _大美  阅读(203)  评论(0编辑  收藏  举报