LightOJ 1197 Help Hanzo(区间素数筛选)

E - Help Hanzo
Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu

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

题意:t组数据,每组数据给定a和b,求ab之间素数的个数。

题解:ab范围是2的31次方,打10^5的素数表筛选即可。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn=1e5+50;
ll prime[maxn],cnt=0;
bool isprime[maxn];
void get() //素筛模板 细节问题要注意
{
    for(int i=2; i<=maxn; i++)
    {
        if(!isprime[i])
        {
            prime[cnt++]=i;
            for(int j=i+i; j<=maxn; j+=i)
                isprime[j]=true;
        }
    }
}
int main()
{
    get();
    int t,cas=1;
    cin>>t;
    while(t--)
    {
        ll a,b; //用int会Re  能long long 就long long
        cin>>a>>b;
        if(a<2) //这里一定要注意 没有这句会wa  1 这个数要跳过去
        a=2;    //1和0既非素数也非合数
        bool vis[maxn];
        memset(vis,0,sizeof(vis));
        for(int i=0; prime[i]*prime[i]<=b; i++)
        {
            ll j;
            j=prime[i]*(a/prime[i]);
            if(j<a)   //这句话相对于上一句一定要后加上 因为a=18 18/2*2=18 不需要加
            j+=prime[i];
            if(j==prime[i]) //这句话相当于上一句一定要后加上 因为a=2 2/5*5=0 0+5=5 5+5=10才对
            j+=prime[i];
            for(; j<=b; j+=prime[i])
                vis[j-a]=1;
        }
        ll ans=0;
        for(int i=a; i<=b; i++)
        if(!vis[i-a])
        ans++;
        printf("Case %d: %d
",cas++,ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Ritchie/p/5296214.html