题目
![](https://i-blog.csdnimg.cn/direct/f8b3b2beefba4b849b0d4df5a4d700a3.png)
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6+10;
int primes[N], cnt;
bool st[N];
void get_primes(int n)
{
memset(st, 0, sizeof st);
cnt = 0;
for(int i = 2; i <= n; i++)
{
if(!st[i]) primes[++cnt] = i;
for(int j = 1; primes[j] * i <= n; j++)
{
st[primes[j] * i] = true;
if(i % primes[j] == 0) break;
}
}
}
int main()
{
int l, r;
while(~scanf("%d%d", &l, &r))
{
get_primes(50000);
memset(st, 0, sizeof st);
for(int i = 1; i <= cnt; i++)
{
LL p = primes[i];
for(LL j = max(2 * p, (l + p - 1) / p * p); j <= r; j += p)
{
st[j-l] = true;
}
}
cnt = 0;
for(int i = 0; i <= r - l; i++)
{
if(!st[i] && i+l > 1) primes[++cnt] = i + l;
}
if(cnt < 2)
{
cout << "There are no adjacent primes." << '\n';
}
else
{
int minp = 1, maxp = 1;
for(int i = 1; i + 1 <= cnt; i++)
{
int d = primes[i+1] - primes[i];
if(d < primes[minp+1] - primes[minp]) minp = i;
if(d > primes[maxp+1] - primes[maxp]) maxp = i;
}
printf("%d,%d are closest, %d,%d are most distant.\n"
, primes[minp], primes[minp+1]
, primes[maxp], primes[maxp+1]);
}
}
}