poj2689Prime Distance 素数筛选

来源:互联网 发布:windows双网卡绑定 编辑:程序博客网 时间:2024/05/29 14:25

poj2689Prime Distance


题目要求:在给定范围L~R中找出差值最大和最小的两组素数


要在L~R筛选素数 ,直接算出1~2,147,483,647的话肯定超时


但实际上,筛选1~2,147,483,647中的素数需要的因子并不多,只要找出2~sqrt(2,147,483,647)中的素数就够了,筛选法就是这么干的


之后用这些素数对L~R的区间试除 得到L~R内的素数 求出结果


#include<iostream>#include<cstdio>#include<cstring>using namespace std;bool Q[1001000];bool p[50000];int P[5000];int main(){__int64 i,j,k,L,R;for(i=2;i<=50000;i+=2)p[i]=0,p[i+1]=1;p[1]=0;p[2]=1;P[1]=2;P[0]=1;for(i=1;i<=46345;i+=2){if(p[i]){int k=i*i;while(k<50000){p[k]=0;k+=2*i;}P[++P[0]]=i;}}while(scanf("%I64d%I64d",&L,&R)!=EOF){int Start;for(i=L;i<=R;i++)Q[i-L]=1;for(i=1;i<=P[0];i++){if(P[i]>=R)break;Start=L/P[i];if(Start*P[i]<L)Start++;if(Start==1)Start++;for(j=Start;j*P[i]<=R;j++)Q[j*P[i]-L]=0;}if(L==1)Q[0]=0,Q[2]=1;if(L==2)Q[0]=1;__int64 pre=R,now=0,min=1000000000,max=0,a,b,x,y;for(i=L;i<=R;i++){if(Q[i-L]){pre=i;break;}}for(i=pre+1;i<=R;i++){if(Q[i-L]){now=i;if(now-pre<min){min=now-pre;a=pre,b=now;}if(now-pre>max){max=now-pre;x=pre,y=now;}pre=now;}}if(!now)printf("There are no adjacent primes.\n");elseprintf("%I64d,%I64d are closest, %I64d,%I64d are most distant.\n",a,b,x,y);}return 0;}/*2000000000 20000000012146483648 2147483647*/




原创粉丝点击