使用C++语言进行编写
时间: 2023-08-04 20:05:57 浏览: 79
好的,下面是使用C++语言实现的代码:
```cpp
#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
bool is_prime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
void find_adjacent_primes(int L, int U) {
int min_gap = numeric_limits<int>::max();
int min_sum = numeric_limits<int>::max();
int max_gap = -1;
int max_sum = -1;
int prev_prime = 0;
for (int i = L; i <= U; i++) {
if (is_prime(i)) {
if (prev_prime != 0) {
int gap = i - prev_prime;
if (gap < min_gap) {
min_gap = gap;
min_sum = prev_prime + i;
cout << "The closest adjacent primes are " << prev_prime << " and " << i << ", with a gap of " << gap << "." << endl;
} else if (gap == min_gap && prev_prime + i < min_sum) {
min_sum = prev_prime + i;
cout << "The closest adjacent primes are " << prev_prime << " and " << i << ", with a gap of " << gap << "." << endl;
}
if (gap > max_gap) {
max_gap = gap;
max_sum = prev_prime + i;
cout << "The farthest adjacent primes are " << prev_prime << " and " << i << ", with a gap of " << gap << "." << endl;
} else if (gap == max_gap && prev_prime + i < max_sum) {
max_sum = prev_prime + i;
cout << "The farthest adjacent primes are " << prev_prime << " and " << i << ", with a gap of " << gap << "." << endl;
}
}
prev_prime = i;
}
}
if (min_gap == numeric_limits<int>::max()) {
cout << "There are no adjacent primes in the given range." << endl;
}
}
int main() {
int L = 1;
int U = 100;
find_adjacent_primes(L, U);
return 0;
}
```
这个程序的输出结果和之前Python版的程序一样。你可以根据需要修改L和U的值来测试不同的区间。
阅读全文