题目描述
路飞请你求出区间 [l,r] 上距离最近的相邻的素数对和距离最远的相邻的素数对。 3,5 是相邻的素数,2,5 不是相邻的素数。距离定义为 2 个素数的差的绝对值。比如 5,7 距离为 2 。
输入
输入 2 个整数 l,r(1≤l≤r≤8000000) 。
输出
如果 a,b(a<b) 是距离最近的素数对,c,d(c<d) 是距离最远的素数对,按照如下格式输出 a,b are closest, c,d are most distant. 。如果最近或者最远有多对,输出 a 和 c 最小的。如果没有相邻是素数对,输出 There are no adjacent primes.
样例输入1
3 10
样例输出1
3,5 are closest, 3,5 are most distant.
样例输入2
14 17
样例输出2
There are no adjacent primes.
#include <iostream>
using namespace std;
int num[8000005];
void init() {
for (int i = 2; i * i <= 8000000; i++) {
if (!num[i]) {
for (int j = 2; i * j <= 8000000; j++) {
num[i * j] = 1;
}
}
}
}
int main() {
init();
int l, r;
cin >> l >> r;
int a = -1, b, c, d, nex;
for (int i = l; i < r; i++) {
if (!num[i]) {
nex = i + 1;
while (num[nex]) {
nex++;
}
if (nex > r) {
break;
}
if (a == -1) {
a = c = i;
b = d = nex;
}
else if (b - a > nex - i) {
a = i;
b = nex;
}
else if (d - c < nex - i) {
c = i;
d = nex;
}
}
}
if (a == -1) {
cout << "There are no adjacent primes." << endl;
}
else cout << a << "," << b << " are closest, " << c << "," << d << " are most distant.";
return 0;
}