题目链接:http://www.spoj.com/problems/PRIME1/en/
埃式筛法的变型--区间筛法;
复杂度为O(nloglogn),就是一个模板而已。
以下是AC代码:
/*
name:Rollchuchy
type:区间筛法
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAX_L=1e6;
const int MAX_SQRT_B=1e6;
typedef long long ll;
bool is_prime[MAX_L];
bool is_prime_small[MAX_SQRT_B];
void segement(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*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;
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
int T;
cin>>T;
while(T--){
ll a,b;
scanf("%lld%lld",&a,&b);
segement(a,b);
for(ll i=a;i<=b;i++){
if(i==1) continue;
if(is_prime[i-a])
printf("%lld\n",i);
}
cout<<endl;
}
return 0;
}