题解 | #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
#include <bits/stdc++.h> #include <climits> using namespace std; int main() { int target; cin >> target; vector<bool> prime(target + 1, true); vector<int> res; for(int i = 2; i <= target; ++i){ if(prime[i]){ res.push_back(i); if(i * i > target) continue; for(int j = i * i; j <= target; j += i){ prime[j] = false; } } } unordered_set<int> set(res.begin(), res.end()); // cout << " 1 " << endl; // for(auto &i : res){ // cout << i << " "; // } //cout << endl; int first = 0, second = 0; int diff = INT_MAX; for(int i = res.size() - 1; i >= 0; --i){ int temp = target - res[i]; auto it = set.find(temp); if(it != set.end()){ diff = abs(*it - res[i]); if(diff <= abs(first - second) || first == 0){ first = *it; second = res[i]; } } } cout << second << endl << first << endl; return 0; } // 64 位输出请用 printf("%lld")