题解 | #查找组成一个偶数最接近的两个素数#

查找组成一个偶数最接近的两个素数

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")

全部评论

相关推荐

2024-11-18 15:57
门头沟学院 Java
最终归宿是测开:这个重邮的大佬在重邮很有名的,他就喜欢打92的脸,越有人质疑他,他越觉得爽😂
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务