Help Hanzo LightOJ - 1197

题目链接:https://cn.vjudge.net/problem/LightOJ-1197

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

题目大意:给定一个区间问你区间内有多少个素数。

思路:先进行素数打表。小于b的合数肯定有一个小于根号b的一个素数因子。然后把这些合数筛出来,筛出来的数组大小为这个数减去a的数,假设a为第一个位置的数要不然数组中存不下来。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+100;
ll prime[maxn],f[maxn];
bool vis[maxn];
int cnt=0;
void get()
{
    memset(prime,0,sizeof(prime));
    memset(vis,false,sizeof(vis));
    for(int i=2;i<=maxn;i++)
    {
        if(!vis[i])
        {
            prime[cnt++]=i;
        }
        for(int j=0;j<cnt&&prime[j]*i<=maxn;j++)
        {
            vis[i*prime[j]]=true;
            if(i%prime[j]==0)
            break;
        }
    }
}
int main()
{
    get();
    int t;
    scanf("%d",&t);
    for(int kcase=1;kcase<=t;kcase++)
    {
        ll a,b;
        memset(f,0,sizeof(f));
        scanf("%lld %lld",&a,&b);
        ll ans=b-a+1;
        for(ll i=0;i<cnt&&prime[i]*prime[i]<=b;i++)
        {
            for(ll j=a/prime[i]*prime[i];j<=b;j+=prime[i])
            {
                if(j>=a&&j>prime[i])
                {
                    f[j-a]=1;
                }
            }
        }
        for(int i=0;i<=b-a;i++)
        {
            if(f[i])
            {
                ans--;
            }
        }
        cout<<"Case "<<kcase<<": "<<(a==1?ans-1:ans)<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/HTallperson/article/details/84309123