poj 2689 线性时间筛选素数

#include <iostream>
#include <algorithm>
#include "stdio.h"
#include "memory.h"
#include <cmath>
using namespace std;


#define N 50010


bool used[1000010];
int p[N];
int cnt = 0;


void Init()
{
    memset(used,false,sizeof(used));
    for (int i = 2; i < N; i++)
    {
        if (!used[i])
        {
            p[cnt] = i;
            cnt++;
        }
        for (int j = 0; j < cnt && i * p[j] < N; j++)
        {
            used[i * p[j]] = true;
            if (i % p[j] == 0)
                break;
        }
    }
}


int res[500000];
int num = 0;
void GetPrime(int L,int R)
{
    memset(used,false,sizeof(used));
    for (int i = 0; i < cnt && p[i] <= sqrt(R * 1.0) + 0.00001; i++)
    {
        int s = L / p[i] + ((L % p[i]) > 0);
        if (s == 1) s = 2;
        for (int j = s; (long long)j * p[i] <= R; j++)
       {
            if ((long long)j * p[i] - L >= 0)
                 used[j * p[i] - L] = true;
            else
                {
            printf("");
            }
       }
    }


    num = 0;
    for (size_t i = L; i <= R; i++)
    {
        if (used[i - L] == false)
        {
            res[num] = i;
            num++;
        }
    }
}


int main()
{
    Init();
 /*   for (int i = 0; i < cnt; i++)
        printf("%d ",p[i]);
    printf("\n");
    cout<<cnt<<endl;*/


    int L,R;
    while (scanf("%d%d",&L,&R) != EOF)
    {
        if (L == 1) L = 2;
        GetPrime(L,R);
        if (num < 2)
            printf("There are no adjacent primes.\n");
        else
        {
            int minDis = res[1] - res[0];
            int s1 = 0;
            int maxDis = res[1] - res[0];
            int s2 = 0;


            for (int i = 1; i < num - 1; i++)
            {
                if (res[i + 1] - res[i] < minDis)
                {
                    s1 = i;
                    minDis = res[i + 1] - res[i];
                }
                if (res[i + 1] - res[i] > maxDis)
                {
                    s2 = i;
                    maxDis = res[i + 1] - res[i];
                }
            }


            printf("%d,%d are closest, %d,%d are most distant.\n",
                res[s1],res[s1 + 1],res[s2],res[s2 + 1]);
        }
 /*       for (int i = 0; i < num; i++)
            printf("%d ",res[i]);
        printf("\n");*/
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值