zoj1842 Prime Distance

//zoj1842 Prime Distance

//Accepted 1842 C ++ 00:00.13 1852K

//Sieve of Eratosthenes

//Sieve is the best prime generator algorithm

//http://www.comp.nus.edu.sg/~stevenha/programming/prog_mathematics.html#Prime%20Numbers

#include <iostream>

#include <string>

using namespace std;

typedef long long elem;

elem plist[4800],pcnt;

 

void getprime()

{

       plist[0] = 2, plist[1] = 3, pcnt = 2;

       for (long n=5,i; n<=47000; n+=2) {

              for (i=1; plist[i]*plist[i]<=n && n%plist[i]; i++);

              if (plist[i]*plist[i] > n) plist[pcnt++] = n;

       }

}

 

bool flag[1000010];

void sieve (elem L, elem U)

{

       elem c[2],d[2],first;

       if (L == 1) L++;

       memset(flag, 1, sizeof(flag[0])*(U-L+1));

       for (elem i=0,j; plist[i]*plist[i]<=U; i++) {

              j = L/plist[i]+(L%plist[i]>0);

              if (j == 1) j++;

              for (j*=plist[i]; j<=U; j+=plist[i]) flag[j-L] = 0;

       }

       c[0] = c[1] = d[0] = d[1] = 0;

       first = 0;

       for (elem i=L; i<=U; i++) {

              if (flag[i-L]) {

                     if (first) {

                            if (!c[0] || c[0] && i-first<c[1]-c[0])

                                   c[0] = first, c[1] = i;

                            if (!d[0] || d[0] && i-first>d[1]-d[0])

                                   d[0] = first, d[1] = i;

                     }

                     first = i;

              }

       }

       if (c[0]) cout << c[0] << "," << c[1] << " are closest, " << d[0] << "," << d[1] << " are most distant." << endl;

       else cout << "There are no adjacent primes." << endl;

}

 

int main()

{

       elem L,U;

       getprime();

      

       while (cin >> L >> U)

              sieve (L,U);

       return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值