Prime Distance
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 12847 |
|
Accepted: 3429 |
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,sqrt(2147483647)]之间的素数,第二遍用这些素数去筛区间[l,r]之间的合数,将素数提取想出来,然后暴力统计答案。注意这题有个坑点,就是l=1的时候,1是无法被筛掉的,因此要特殊处理。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#define Maxn 200010
#define ll long long
using namespace std;
int c[Maxn],prime[Maxn],p[Maxn],vis[Maxn*5];
int tot=0;
const int inf=0x3f3f3f3f;
void Euler(int n){
memset(c,0,sizeof c);
for(int i=2;i<=n;i++){
if(!c[i]) prime[tot++]=i;
for(int j=0;j<tot;j++){
if(i*prime[j]>n) break;
c[i*prime[j]]=1;
if(i%prime[j]==0) break;
}
}
}
int main()
{
ll l,r;
Euler(46350);
while(~scanf("%lld%lld",&l,&r)){
memset(vis,0,sizeof vis);
if(l==1) vis[0]=1;
for(int i=0;i<tot;i++){
ll j=l/prime[i]*prime[i];
if(j<l) j+=prime[i];
if(j==prime[i]) j+=prime[i];
for(;j<=r;j+=prime[i])
vis[j-l]=1;
}
int tot1=0;
for(int i=0;i<=r-l;i++)
if(!vis[i]) p[tot1++]=i+l;
int minn=inf,maxx=-inf,mina,maxa,minb,maxb;
if(tot1==1) puts("There are no adjacent primes.");
else{
for(int i=0;i<tot1-1;i++){
if(p[i+1]-p[i]<minn) minn=p[i+1]-p[i],mina=p[i],maxa=p[i+1];
if(p[i+1]-p[i]>maxx) maxx=p[i+1]-p[i],minb=p[i],maxb=p[i+1];
}
printf("%d,%d are closest, %d,%d are most distant.\n",mina,maxa,minb,maxb);
}
}
return 0;
}