M - 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
题解:
区间素数筛。
用了挑战程序设计里的模板。
注意当起始区间为1时 应减去1
代码:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn = 2e5+10;
typedef long long ll;
bool is_prime[maxn];
bool is_prime_small[maxn];
ll prime_num;
void segment_sieve(ll a,ll b)
{
for(ll i=0;(ll)i*i<=b;i++) is_prime_small[i]=true;
for(ll i=0;i<=b-a;i++) is_prime[i]=true;
for(ll i=2;(ll)i*i<=b;i++)
{
if(is_prime_small[i])
{
for(ll j=2*i;(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;
}
}
for(ll i=0;i<=b-a;++i) //统计个数
if(is_prime[i]) prime_num++;
}
int main()
{
int T;
scanf("%d",&T);
int ks=1;
while(T--)
{
prime_num=0;
ll a,b;
cin>>a>>b;
segment_sieve(a,b);
if(a==1) prime_num--;
printf("Case %d: %lld\n",ks++,prime_num);
}
return 0;
}