题目:http://acm.hit.edu.cn/hoj/problem/view?id=1552
本题求一段区间内距离最近和最远的素数对儿。
先求出[1,50000]内的素数,然后进行生成更大范围内的素数。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
#define N 500000
long long prim[2000200];
long long visited[1000100];
long long flag[1000100];
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
long long l,r;
while(scanf(" %lld %lld",&l,&r) == 2)
{
long long num = 0;
long long Max = 3000000000;
long long Min = 0;
long long Max1,Max2;
long long Min1,Min2;
memset(visited,0,sizeof(visited));
memset(flag,0,sizeof(flag));
memset(prim,0,sizeof(prim));
for(long long i=2; i<=N; i++)
{
if(visited[i] == 0)
{
prim[num++] = i;
}
for(long long j=0; j<num && prim[j]*i<=N; j++)
{
visited[prim[j]*i] = 1;
if(i%prim[j] == 0)
{
break;
}
}
}
if(r<=N)
{
int flag = 0;
for(long long i=0; i<num-1 && prim[i]<=r; i++)
{
if(prim[i]>=l && prim[i+1]<=r)
{
flag = 1;
if(prim[i+1] - prim[i]<Max)
{
Max = prim[i+1] - prim[i];
Max1 = prim[i];
Max2 = prim[i+1];
}
if(prim[i+1] - prim[i]>Min)
{
Min = prim[i+1] - prim[i];
Min1 = prim[i];
Min2 = prim[i+1];
}
}
}
if(flag == 1)
{
printf("%lld,%lld are closest, %lld,%lld are most distant.\n",Max1,Max2,Min1,Min2);
}
else
{
printf("There are no adjacent primes.\n");
}
continue;
}
int flag2 = 0;
long long l2 = l;
if(l<=N)
{
l = N + 1;
}
for(long long i=0; prim[i] * prim[i]<=r; i++)
{
long long start = 0;
if(l%prim[i] == 0)
{
start = l;
}
else
{
start = (l/prim[i]+1)*prim[i];
}
for(; start<=r; start+=prim[i])
{
flag[start-l] = 1;
}
}
for(long long i=l; i<=r; i++)
{
if(flag[i-l] == 0)
{
prim[num++] = i;
}
}
for(long long i=0;i<num-1 && prim[i]<=r; i++)
{
if(prim[i]>=l2 && prim[i+1]<=r)
{
flag2 = 1;
if(prim[i+1] - prim[i]<Max)
{
Max = prim[i+1] - prim[i];
Max1 = prim[i];
Max2 = prim[i+1];
}
if(prim[i+1] - prim[i]>Min)
{
Min = prim[i+1] - prim[i];
Min1 = prim[i];
Min2 = prim[i+1];
}
}
}
if(flag2 == 1)
{
printf("%lld,%lld are closest, %lld,%lld are most distant.\n",Max1,Max2,Min1,Min2);
}
else
{
printf("There are no adjacent primes.\n");
}
}
return 0;
}