POJ2689——Prime Distance(大区间素数筛)
来源:互联网 发布:2017怎么申请开淘宝店 编辑:程序博客网 时间:2024/05/23 16:55
题目链接
题目要求给定区间内求最小和最大间距的素数对,如果没有则输出 There are no adjacent primes.但由于给定区间太大,所以不可能在给定的区间内直接暴力,而要先求出给定区间内的素数,由于区间大小不超过1000000,所以可以对该区间用素数筛法,因为区间在21亿,所以区间内的合数的质因子都在2~√2147483647内,所以先素数筛出1到50000内的素数,再用这些素数去筛给定区间的素数,再对筛好素数的给定区间暴力即可。
#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<algorithm>using namespace std;typedef long long LL;bool vis[50005]={0};LL prim[6000]={0};LL Pr[1000005]={0};int k=0;LL temp[1000005]={0};void init(){ int m=sqrt(50000.5); for(int i=2;i<=m;i++)if(!vis[i]) for(int j=i*i;j<=50000;j+=i)vis[j]=1; for(int i=2;i<=50000;i++) if(!vis[i])prim[k++]=i;}int main(){ //freopen("in.in","r",stdin); //freopen("out.out","w",stdout); LL L, U; init(); while(scanf("%lld%lld",&L,&U)!=EOF) { if(L==1)L=2; for(int i=0;i<k;i++) { LL a=L/prim[i]; if(L%prim[i])a++; LL b=U/prim[i]; for(LL j=a;j<=b;j++) { if(j*prim[i]!=prim[i])//防止素数把自己本身给筛掉 temp[j*prim[i]-L]=1;//由于区间上限太大,但区间大小较小,改用区间第几位来标记是否为素数 } } memset(Pr,0,sizeof(Pr)); int t=0; for(LL i=L;i<=U;i++) { if(temp[i-L]==0) Pr[t++]=i; } //printf("%d\n",t); LL maxn=0; LL minn=10000000; LL xa=0,ya=0; LL xi=0,yi=0; for(int i=1;i<t;i++) { if(maxn<Pr[i]-Pr[i-1]) { maxn=Pr[i]-Pr[i-1]; xa=Pr[i-1]; ya=Pr[i]; } if(minn>Pr[i]-Pr[i-1]) { minn=Pr[i]-Pr[i-1]; xi=Pr[i-1]; yi=Pr[i]; } } if(maxn==0) printf("There are no adjacent primes.\n"); else printf("%lld,%lld are closest, %lld,%lld are most distant.\n",xi,yi,xa,ya); memset(temp,0,sizeof(temp)); } return 0;}
0 0
- POJ2689——Prime Distance(大区间素数筛)
- POJ2689:Prime Distance(大区间素数)
- POJ2689 Prime distance 素数
- POJ2689 Prime Distance 素数距离
- Prime Distance(poj2689变形的筛法素数)
- poj 2689 Prime Distance(大区间筛素数)
- POJ 2689 Prime Distance 【大区间筛素数】
- poj2689 Prime Distance 素数筛选应用 复习
- poj2689(Prime Distance两次筛)
- 大区间素数筛选 POJ2689
- Poj 2689 Prime Distance【素数区间筛】
- POJ2689 Prime Distance
- poj2689 Prime Distance
- POJ2689 Prime Distance
- poj2689 Prime Distance
- 【数论】poj2689 Prime Distance
- POJ2689 Prime Distance
- poj2689 Prime Distance
- 命名规范
- 文件的分割
- Android中日期选择器与时间选择器的实现
- C语言再学习 -- printf、scanf占位符
- angularjs 单选按钮 默认选中
- POJ2689——Prime Distance(大区间素数筛)
- Shortest substring containing three short strings
- 【机房收费】概况总结
- ZooKeeper实战应用之【统一配置管理】
- Lancome5_order
- WPF的binding
- fail-fast机制
- 监控mysql主从状态邮件报警脚本
- Activity