poj 2689 区间素数筛(注意1的情况)

点击打开链接

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
typedef pair<int,int>PII;
const int maxc=65536;
const int maxn=1e6+10;
int prime[maxc],cnt=0;
bool p1[maxc];
bool p[maxn];
void is_prime()
{
    memset(p1,true,sizeof(p1));
    p1[0]=p1[1]=false;
    for(int i=2;i<=maxc;i++)
         if(p1[i]) {
           prime[cnt++]=i;
           for(LL j=(LL)i*i;j<=maxc;j+=i)
                p1[j]=false;
    }
}
int main()
{
    is_prime();
    int a,b;
    while(scanf("%d%d",&a,&b)==2)
    {
        memset(p,true,sizeof(p));
        int k=floor(sqrt(b)+0.5);
        int p1=lower_bound(prime,prime+cnt,k)-prime;
        for(int i=0;i<=p1;i++)
        {
            int st=max((LL)a/prime[i]*prime[i],(LL)prime[i]*prime[i]);
            for(LL j=st;j<=b;j+=prime[i])
                if(j>=a) p[j-a]=false;
        }
         if(a==1) p[0]=false;
         LL ans=0;                 //素数个数
         PII m1,m2;
         int little=maxn,big=0;
         int last=-1;
         for(int i=0;i<=b-a;i++)
             if(p[i]) {
               ans++;
               if(last==-1) last=i;
               else {
                      if(i-last<little) {
                        little=i-last;
                        m1.first=last+a;
                        m1.second=i+a;
                      }
                      if(i-last>big) {
                        big=i-last;
                        m2.first=last+a;
                        m2.second=i+a;
                      }
                      last=i;
               }
           }
         if(ans==1) printf("There are no adjacent primes.\n");
         else printf("%d,%d are closest, %d,%d are most distant.\n",m1.first,m1.second,m2.first,m2.second);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值