问题 F: 【素数】Prime Distance
时间限制: 1 Sec 内存限制: 128 MB提交: 22 解决: 7
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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).
输入
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.
输出
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.
样例输入
2 17 14 17
样例输出
2,3 are closest, 7,11 are most distant. There are no adjacent primes.
思路:先用埃氏筛筛出1到sqrt(r)的素数,再以此筛出a到b的素数。
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> using namespace std; template <class T> inline void rd(T &ret){ char c; ret = 0; while ((c = getchar()) < '0' || c > '9'); while (c >= '0' && c <= '9'){ ret = ret * 10 + (c - '0'), c = getchar(); } } const int maxn=1e6+1e3; const int lim=50001; bool hv[lim],prime[maxn]; int len,l,r; void seg(long long l,long long r){ len=r-l+1; for(int i=0;i<len;i++)prime[i]=1; if(1-l>=0) prime[1-l]=0; for(long long i=2;i*i<=r;i++){ if(hv[i]){ for(long long j=max((long long)2,(l-1+i)/i)*i;j<=r;j+=i){ prime[j-l]=0; } } } } int main() { for(int i=2;i<lim;i++)hv[i]=1; for(int i=2;i*i<lim;i++){ if(hv[i]){ for(int j=i*2;j<lim;j+=i){ hv[j]=0; } } } while(~scanf("%d%d",&l,&r)){ seg(l,r); int lx,rx,li,ri,minn=(1<<30),maxn=-1,cur=-1; for(int i=0;i<len;i++){ if(prime[i]){ if(cur>=0){ if(minn>i-cur)minn=i-cur,li=cur+l,ri=i+l; if(maxn<i-cur)maxn=i-cur,lx=cur+l,rx=i+l; cur=i; } else cur=i; } } if(maxn>0) printf("%d,%d are closest, %d,%d are most distant.\n",li,ri,lx,rx); else puts("There are no adjacent primes."); } return 0; }