Prime Distance
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
3s | 8192K | 46 | 17 | Standard |
Your program is given 2 numbers: L and U (1<=L<U<=2,147,483,647), and you are to find the two adjacent primes C1 and C2 (L<=C1<C2<=U) that are closest (i.e. C2-C1 is the minimum). If there are other pairs that are the same distance apart, use the first pair. You are also to find the two adjacent primes D1 and D2 (L<=D1<D2<=U) where D1 and D2 are as distant from each other as possible (again choosing the first pair if there is a tie).
Input
Each line of input will contain two positive integers, L and U, with L < U. The difference between L and U will not exceed 1,000,000.Output
For each L and U, the output will either be the statement that there are no adjacent primes (because there are less than two primes between the two given numbers) or a line giving the two pairs of adjacent primes.Sample Input
2 17 14 17
Output for Sample Input
2,3 are closest, 7,11 are most distant. There are no adjacent primes.
Submit / Problem List / Status / Discuss
#include<stdio.h>
#include<string.h>
int prime[46400],pnum,L,U;
int lnum,luprime[1000005];
bool pri[46400],lupri[1000005];
void init()
{
memset(pri,true,sizeof(pri));
pri[0]=false;pri[1]=false;
for(int i=2;i*i<46400;i++)
{
if(pri[i])
{
for(int j=i*i;j<46400;j+=i)
pri[j]=false;
}
}
pnum=0;
for(int i=2;i<46400;i++)
if(pri[i]) prime[pnum++]=i;
}
void getprime()
{
lnum=0;
long long i,j;
if(U<46400)
{
for(i=L;i<=U;i++)
if(pri[i]) luprime[lnum++]=i;
}
else
{
long long begin,end=U-L+1;
memset(lupri,true,sizeof(lupri));
for( i=(L%2==0?0:1);i<end;i+=2) lupri[i]=false;
for( i=1;i<pnum;i++)
{
begin=L/prime[i]*prime[i];
if(begin<L) begin+=prime[i];
begin-=L;
for(j=begin;j<end;j+=prime[i])
lupri[j]=false;
}
for(i=0;i<end;i++)
if(lupri[i]) luprime[lnum++]=i+L;
}
}
void print()
{
if(lnum<2) printf("There are no adjacent primes./n");
else{
int mina,minb,maxa,maxb,min=10000000,max=-100;
for(int i=1;i<lnum;i++)
{
if(luprime[i]-luprime[i-1]<min)
{
min=luprime[i]-luprime[i-1];
mina=luprime[i];
minb=luprime[i-1];
}
if(luprime[i]-luprime[i-1]>max)
{
max=luprime[i]-luprime[i-1];
maxa=luprime[i];
maxb=luprime[i-1];
}
}
printf("%d,%d are closest, %d,%d are most distant./n",minb,mina,maxb,maxa);
}
}
int main()
{
init();
while(scanf("%d%d",&L,&U)!=EOF)
{
getprime();
print();
}
return 0;
}