题意:求a~b之间的素数;(1<=a<b<2^31)
难点:数据太大,素数打表会TLE,枚举会MLE;
解题关键:b-a<=1e5;
方法:素数打表小部分(1e6),然后用已打表素数去拓展所给区间的素数,用v[j-a](a<=j<=b)来标记是否是素数,就不会MLE
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=1e6+5;
int tot=0,ans[N/10];
bool vis[N],v[N];
void primer()
{
memset(vis,true,sizeof(vis));
for(int i=2;i<N;++i)
{
if(vis[i]) ans[++tot]=i;
for(int j=1;(j<=tot)&&(i*ans[j]<N);++j)
{
vis[i*ans[j]]=false;
if(i%ans[j]==0) break;
}
}
}
int main()
{
primer();
int t,a,b,cas=1;
scanf("%d",&t);
while(t--)
{
int bns=0,max,min;
scanf("%d%d",&a,&b);
if(b<N)
{
min=lower_bound(ans+1,ans+tot+1,a)-ans;
max=upper_bound(ans+1,ans+tot+1,b)-ans;
bns=max-min;
}
else{
memset(v,true,sizeof(v));
for(int i=1;(i<=tot)&&(ans[i]<a);++i)
{
ll k=a/ans[i];
if(a%ans[i]) k++;
for(ll j=k*ans[i];j<=b;j+=ans[i])
v[j-a]=false;
}
for(int k=0;k<=b-a;++k)
if(v[k]) bns++;
}
printf("Case %d: %d\n",cas++,bns);
}
}
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 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).
For each case, print the case number and the number of safe territories.
3
2 36
3 73
3 11
Case 1: 11
Case 2: 20
Case 3: 4