题目
题目描述
英文题目
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 \leqslant L< U \leqslant 2,147,483,647$), and you are to find the two adjacent primes $C1$ and $C2$ ($L \leqslant C1< C2 \leqslant 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 \leqslant D1< D2 \leqslant U$) where $D1$ and $D2$ are as distant from each other as possible (again choosing the first pair if there is a tie).
中文题意
给定两个整数$L,R$($1 \leqslant L< R \leqslant 2,147,483,647$),求闭区间 $\left[L,R\right]$中相邻两个质数的差的最小值和最大值是多少,分别输出这两对质数。
输入输出格式
输入格式
每行两个整数$L,R$($1 \leqslant L< R \leqslant 2,147,483,647,R-L \leqslant 10^6$)。
输出格式
对于每个$L,R$,输出最小值和最大值,格式参照样例。若区间内无质数,输出”There are no adjacent primes.”。
输入输出样例
输入样例
2 17
14 17
输出样例
2,3 are closest, 7,11 are most distant.
There are no adjacent primes.
题解
由于$L,R$的范围很大,所以埃氏筛法和欧拉筛法都无法生成$\left[1,R\right]$的所有质数。但是$R-L$的范围很小且任何一个合数$n$一定包含一个不超过$\sqrt{n}$的质因子,所以我们只需要用筛法求出$2,3,\cdots,\sqrt{n}$的所有质数。而对于每一个质数$p$,标记$i \times p \left(\left\lceil\frac{L}{p}\right\rceil \leqslant i \leqslant \left\lceil\frac{R}{p}\right\rceil\right)$为合数。标记完后,剩下的所有数就是$\left[L,R\right]$中的质数了。再两两比较,找出差最大和最小的就可以了。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m,i,j,t1,t2,x1,x2,y1,y2,l,r,a[100001], b[1000001];
bool v[1000001];
void prime()//筛出2~46340之间的质数
{
memset(v,1,sizeof(v));
for(i=2;i<=46340;i++) if(v[i]){
a[++n]=i;
for(j=2;j<=46340/i;j++) v[i*j]=false;
}
}
int main()
{
prime();
while(cin>>l>>r){
memset(v,1,sizeof(v));
if(l==1) v[0]=false;
for(i=1;i<=n;i++) for(j=l/a[i];j<=r/a[i];j++) if(j>1) v[a[i]*j-l]=false;//去除L~R中的合数
m=0;
for(i=l;i<=r;i++){
if(v[i-l]) b[++m]=i;//存储L~R中的质数
if(i==r) break;
}
t1=2147483647;
t2=0;
for(i=1;i<m;i++){
j=b[i+1]-b[i];
if(j<t1){
t1=j;
x1=b[i];
y1=b[i+1];
}
if(j>t2){
t2=j;
x2=b[i];
y2=b[i+1];
}
}//比较差的大小
if(!t2) cout<<"There are no adjacent primes."<<endl;
else cout<<x1<<","<<y1<<" are closest, "<<x2<<","<<y2<<" are most distant."<<endl;
}
return 0;
}
喜欢的话,给博主赏一杯冰阔乐吧~