POJ2689——Prime Distance(大区间素数筛)

题目链接

        题目要求给定区间内求最小和最大间距的素数对,如果没有则输出 There are no adjacent primes.但由于给定区间太大,所以不可能在给定的区间内直接暴力,而要先求出给定区间内的素数,由于区间大小不超过1000000,所以可以对该区间用素数筛法,因为区间在21亿,所以区间内的合数的质因子都在2~√2147483647内,所以先素数筛出1到50000内的素数,再用这些素数去筛给定区间的素数,再对筛好素数的给定区间暴力即可。


#include
#include
#include
#include
#include

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;iPr[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;
}


你可能感兴趣的:(————算法————,数论)