题解 | #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
#include <climits> #include <iostream> #include <cmath> #include <vector> using namespace std; bool isPrime(int num) { if (num <= 1) return false; if (num <= 3) return true; if (num % 2 == 0 || num % 3 == 0) return false; int i = 5; while (i*i <= num){ if (num % i == 0 || num % (i+2) == 0) return false; i += 6; } return true; } int main () { int input; cin >> input; vector<int> vecPrime; for (int i = 2; i <= input; i++){ if (isPrime(i)){ vecPrime.push_back(i); // cout << i << endl; } } int tmp = INT_MAX; int n = INT_MAX,m = INT_MAX; for (int i = vecPrime.size() - 1; i >= 0; i--){ for (int j = i ; j < vecPrime.size(); j++){ if ((vecPrime[i] + vecPrime[j] == input) && tmp > abs(vecPrime[i] - vecPrime[j])){ tmp = abs(vecPrime[i] - vecPrime[j]); n = vecPrime[i]; m = vecPrime[j]; break; } } } if (n!=INT_MAX) { cout << n << endl; cout << m << endl; } return 0; }