1928: Prime Distance
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
3s | 8192K | 72 | 23 | Standard |
The branch of mathematics called number theory is about properties ofnumbers. One of the areas that has captured the interest of numbertheoreticians for thousands of years is the question of primality. Aprime number is a number that is has no proper factors (it is onlyevenly divisible by 1 and itself). The first prime numbers are2,3,5,7 but they quickly become less frequent. One of the interestingquestions is how dense they are in various ranges. Adjacent primesare two numbers that are both primes, but there are no other primenumbers between the adjacent primes. For example, 2,3 are the onlyadjacent primes that are also adjacent numbers.
Your program is given 2 numbers: L and U(1<=L<U<=2,147,483,647), and you are to find the twoadjacent primes C1 and C2 (L<=C1<C2<=U) that are closest(i.e. C2-C1 is the minimum). If there are other pairsthat are the same distance apart, use the first pair. You arealso 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 (againchoosing the first pair if there is a tie).
Input
Each line of input will contain two positive integers, L andU, with L < U. The difference between L and U willnot exceed 1,000,000.Output
For each L and U,the output will either be the statement that there are no adjacentprimes (because there are less than two primes between the two givennumbers) 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.
-
#include <stdio.h>
#include <math.h>
bool prime2[1000010];
bool prime1[50000];
int prime3[1000010];
int main ()
{
long long L,U;
for(int i=3;i<50000;i++)
if(i%2==0) prime1[i]=0;
else prime1[i]=1;
for(int i=3;i*i<=50000;i+=2)
if(prime1[i])
{
for(int j=i*i;j<50000;j+=i)
prime1[j]=0;
}
prime1[2]=1;
while(scanf("%lld%lld",&L,&U)==2)
{
for(long long i=L;i<=U;i++)
if(i%2==0) prime2[i-L]=0;
else prime2[i-L]=1;
if(L==2) prime2[0]=1;
if(L==1) { prime2[1]=1; prime2[0]=0;}
//printf("!!!%lf\n",sqrt(U+0.0));
for(int i=3;i<=sqrt(U+0.0);i+=2)
if(prime1[i])
{
//printf("%d\n",i);
for(long long j=(L/i>2?L/i:2)*i;j<=U;j+=i)
if(j>=L) prime2[j-L]=0;
}
int cnt=0,min=10000000,max=-1;
int x1=0,y1=0,x2=0,y2=0;
for(int i=0;i<=U-L;i++)
if(prime2[i]) prime3[cnt++]=i+L;
if(cnt<=1) printf("There are no adjacent primes.\n");
else
{
for(int i=0;i<cnt-1;i++)
{
if(prime3[i+1]-prime3[i]<min) {x1=prime3[i],y1=prime3[i+1],min=prime3[i+1]-prime3[i];}
if(prime3[i+1]-prime3[i]>max) {x2=prime3[i],y2=prime3[i+1],max=prime3[i+1]-prime3[i];}
}
printf("%d,%d are closest, %d,%d are most distant.\n",x1,y1,x2,y2);
}
}
return 0;
}