Prime Distance
题目
解析
发现 L L L和 R R R都大到不可做,但 R − L R-L R−L却被限制在了 1000000 1000000 1000000以内,考虑筛出 2 2 2到 R \sqrt R R内的质数,然后每次筛出 L L L至 R R R的合数,最后线性跑一下就好了
code:
#include<cmath>
#include<cstdio>
#include<cstring>
using namespace std;
int p[1000010],tot;
long long l,r,a,b,c,d,la,mx,mn;
bool v[1000010];
int main()
{
for(register int i=2;i<=1000000;i++)
{
if(!v[i])p[++tot]=i;
for(register int j=1;j<=tot&&i*p[j]<=1000000;){v[i*p[j]]=1;if(!(i%p[j++]))break;}
}
while(~scanf("%lld%lld",&l,&r))
{
memset(v,1,sizeof(v)),v[0]=(l!=1),la=mx=0,mn=1000000000000000000ll;
for(register int i=1;i<=tot;++i)for(register long long j=l/p[i];j*p[i]<=r;++j)if(j>1&&j*p[i]>=l)v[j*p[i]-l]=0;
for(register long long i=l;i<=r;++i)if(v[i-l]){if(la){if(mn>i-la)mn=i-la,a=la,b=i;if(mx<i-la)mx=i-la,c=la,d=i;};la=i;}
if(mx)printf("%lld,%lld are closest, %lld,%lld are most distant.\n",a,b,c,d);
else printf("There are no adjacent primes.\n");
}
return 0;
}