Prime Distance
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.
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<cstring> 5 const int maxn=50000+10; 6 using namespace std; 7 int p[maxn],a[maxn],f[1000000+10],t=0; 8 void prepare(){ 9 int m=(int)sqrt(50000); 10 for(int i=2;i<=m;i++) 11 if(!p[i]) 12 for(int j=i*i;j<=50000;j+=i)p[j]=1; 13 for(int i=2;i<=50000;i++)if(!p[i])a[++t]=i; 14 } 15 int main(){ 16 prepare(); 17 int L,U; 18 while(scanf("%d%d",&L,&U)!=EOF){ 19 if(L<2)L=2; 20 memset(f,0,sizeof(f)); 21 for(int i=1;i<=t;i++){ 22 int s=(L)/a[i],t=U/a[i]; 23 if(L%a[i])s++; //这步是必须的,不然会出现j*a[i]-L<0 而出现runtime error 24 if(s<2)s=2; 25 for(int j=s;j<=t;j++)f[j*a[i]-L]=1; 26 } 27 int p=-1,max_ans=-1,min_ans=1000000000,x1,y1,x2,y2; 28 for(int i=0;i<=U-L;i++){ 29 if(f[i]==0){ 30 if(p==-1){p=i;continue;} 31 if(max_ans<i-p){max_ans=i-p;x1=p+L;y1=i+L;} 32 if(min_ans>i-p){min_ans=i-p;x2=p+L;y2=i+L;} 33 p=i; 34 } 35 } 36 if(max_ans==-1)cout<<"There are no adjacent primes."<<endl; 37 else cout<<x2<<","<<y2<<" are closest, "<<x1<<","<<y1<<" are most distant."<<endl; 38 } 39 return 0; 40 }