Help Hanzo LightOJ - 1197(区间筛素数模板题)

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

模板
code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX = 1e5+10;
const int MAX_INTERVAL = 2e5+100;
bool is_prime[MAX_INTERVAL];
bool is_prime_small[MAX];
int segment_sieve(ll a,ll b){
    for(int i = 0; (ll)i * i <= b; i++) is_prime_small[i] = true;
    for(int i = 0; i <= b - a; i++) is_prime[i] = true;

    for(int i = 2; (ll)i * i <= b; i++){
       if(is_prime_small[i]){
          for(int j = 2 * j; (ll)j * j <= b; j += i)
            is_prime_small[j] = false;
          for(ll j = max(2LL,(a+i-1)/i)*i; j <= b; j += i)
            is_prime[j-a] = false;
      //找到a-b范围内第一个i到倍数将其划去,记录到时候仍然记录离散化后的数组位置
       }
    }
    int ans = 0;
    for(int i = 0; i <= b-a; i++){
       if(is_prime[i]) ans++;
    }
    return ans;
}
int main(){
   int T,cas = 0;
   scanf("%d",&T);
   while(T--){
      ll a,b;
      scanf("%lld%lld",&a,&b);
      int ans = segment_sieve(a,b);
      if(a == 1) ans--;
      printf("Case %d: %d\n",++cas,ans);
   }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/codeswarrior/article/details/81051757