Prime Distance
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 14881 |
|
Accepted: 3948 |
Description
The branch of mathematics called number theory is about properties of numbers. One of the areas that has captured the interest of number theoreticians for thousands of years is the question of primality. A prime number is a number that is has no proper factors (it is only evenly divisible by 1 and itself). The first prime numbers are 2,3,5,7 but they quickly become less frequent. One of the interesting questions is how dense they are in various ranges. Adjacent primes are two numbers that are both primes, but there are no other prime numbers between the adjacent primes. For example, 2,3 are the only adjacent 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 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
Sample Output
2,3 are closest, 7,11 are most distant.
There are no adjacent primes.
//看大神的博客的,感觉好机智
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define N 1000010
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
int v[N];
ll p[N];
ll pp[N];
ll k,l,u;
void getp()
{
memset(v,0,sizeof(v));
v[1]=1;
k=0;
for(ll i=2;i<=50012;i++)
{
if(!v[i])
{
p[++k]=i;
for(ll j=i*i;j<50001;j+=i)
v[j]=1;
}
}
}
void getpp()
{
ll t;
memset(v,0,sizeof(v));
for(ll i=1;i<=k;i++)
{
t=l/p[i];
while(t*p[i]<l||t<=1)
t++;
for(ll j=t*p[i];j<=u;j+=p[i])
{
if(j>=l)
v[j-l]=1;
}
}
if(l==1)
v[0]=1;
}
int main()
{
getp();
ll i;
while(scanf("%lld%lld",&l,&u)!=EOF)
{
getpp();
ll cnt=0;
for(i=0;i<=u-l;i++)
{
if(!v[i])
pp[++cnt]=i+l;
}
if(cnt<=1)
{
printf("There are no adjacent primes.\n");
continue;
}
ll min=INF,max=-INF;
ll aa,bb,cc,dd;
for(i=1;i<cnt;i++)
{
if(pp[i+1]-pp[i]<min)
{
min=pp[i+1]-pp[i];
aa=pp[i];
bb=pp[i+1];
}
if(pp[i+1]-pp[i]>max)
{
max=pp[i+1]-pp[i];
cc=pp[i];
dd=pp[i+1];
}
}
printf("%lld,%lld are closest, %lld,%lld are most distant.\n",aa,bb,cc,dd);
}
return 0;
}