1. 程式人生 > >Help Hanzo 素數篩+區間列舉

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

思路:

打出10^6的素數篩,再打一個10^6的陣列列舉a--b的情況。

從素數篩開始直接找到某個素數大於a的最小值,往上篩。統計陣列的情況。區間包括1的時候特判-1.

#include <iostream>
#include<stdio.h>
#include<bits/stdc++.h>
#define ll long long

using namespace std;
ll isprime[1000006],prime[1000006],dp[1000006],ans,top,t;
ll s,e,sum;
void check()
{
    isprime[1]=1;
    for(int i=2; i<1000006; i++)
    {
        if(isprime[i]==0)
        {
            prime[ans++]=i;
            for(int j=i+i; j<1000006; j+=i)
                isprime[j]=1;
        }
    }
}
int main()
{
    check();
    scanf("%lld",&t);
    while(t--)
    {
        memset(dp,0,sizeof(dp));
        scanf("%lld%lld",&s,&e);
        sum=0;
        for(int i=0; i<ans&&prime[i]<=e; i++)
        {
            ll gg=s/prime[i];
            gg=prime[i]*gg;
            while(gg<s||gg<=prime[i])
                gg+=prime[i];
            for(ll k=gg; k<=e; k+=prime[i])
            {
                if(k-s<0)
                    continue;
                dp[k-s]=1;
            }
        }
        for(ll i=s; i<=e; i++)
        {
            if(dp[i-s]==0)
                sum++;
        }
        if(s==1)
        sum--;
        printf("Case %lld: %lld\n",++top,sum);
    }
    return 0;
}