题目:http://poj.org/problem?id=2689
源代码:
#include <stdio.h>
__int64 l,u;
int prime[47000];
int prime1[1000100];
int is[47000],is1[1000100];
int cou=0,cou1;
int min,max;
int a,b;
void getPrime()
{
for(int i=2;i<46400;i++) is[i]=1;
for(int i=2;i<46400;i++)
{
if(is[i]) prime[cou++]=i;
for(int j=0;j<cou&&i*prime[j]<46400;j++)
{
is[i*prime[j]]=0;
if(i%prime[j]==0) break;
}
}
}
void solve(__int64 l,__int64 u)
{
__int64 p,s;
if(u<46400)
{
for(int i=l;i<=u;i++)
if(is[i])
prime1[cou1++]=i-l;
}
else
{
for(int i=0;i<=u-l;i++) is1[i]=1;
for(int i=0;i<cou&&prime[i]*prime[i]<=u;i++)
{
s=l/prime[i];
if(s*prime[i]<l) s++;
if(s<=1) s++;
for(__int64 j=s;j*prime[i]<=u;j++)
{
// printf("%I64d\n",j*prime[i]);
p=(int)j*prime[i]-l;
is1[p]=0;
}
}
for(int i=0;i<=u-l;i++)
if(is1[i])
prime1[cou1++]=i;
}
}
int main()
{
// freopen("D:\\in.txt","r",stdin);
getPrime();
while(scanf("%lld %lld",&l,&u)!=EOF)
{
cou1=0;
solve(l,u);
min=2147483647;
max=-1;
if(cou1<2)
{
printf("There are no adjacent primes.\n");
continue;
}
for(int i=0;i<cou1-1;i++)
{
if(prime1[i+1]-prime1[i]<min)
{
min=prime1[i+1]-prime1[i];
a=i;
}
if(prime1[i+1]-prime1[i]>max)
{
max=prime1[i+1]-prime1[i];
b=i;
}
}
printf("%I64d,%I64d are closest, %I64d,%I64d are most distant.\n",prime1[a]+l,prime1[a+1]+l,prime1[b]+l,prime1[b+1]+l);
}
}