素数——POJ-2689
题目代码
#include<stdio.h> #include<iostream> #include<string.h> #include<math.h> using namespace std; typedef long long LL; const int maxn=5e4+7; const int maxm=1000007; int prime[maxn]; bool check[maxm]; int cnt=0; void Prime(){ for(int i=2;i<maxn;i++) if(!check[i]){ prime[cnt++]=i; for(int j=2;j*i<maxn;j++) check[j*i]=true; } } LL l,r; int main(){ Prime(); while(~scanf("%lld%lld",&l,&r)){ int flag=0; if(l==1)l=2; LL minl,minr,maxl,maxr,pre=-1; memset(check,false,sizeof(check)); for(int i=0;i<cnt;i++){ LL a=(l-1)/prime[i]+1,b=r/prime[i]; for(LL j=a;j<=b;j++) if(j>1){ check[j*prime[i]-l]=true; } } for(LL i=0;i<=r-l;i++){ if(!check[i]&&!flag){ flag++; minl=maxl=i; } else if(!check[i]){ flag++; if(flag==2){ minr=maxr=i; } else{ if(i-pre<minr-minl)minr=i,minl=pre; if(i-pre>maxr-maxl)maxr=i,maxl=pre; } pre=i; } } if(flag<2)printf("There are no adjacent primes.\n"); else printf("%lld,%lld are closest, %lld,%lld are most distant.\n",minl+l,minr+l,maxl+l,maxr+l); } return 0; }