40分 还有好多TLE!!!

P1579 哥德巴赫猜想(升级版)

Lipearc @ 2024-12-10 15:09:41

#include<bits/stdc++.h>
using namespace std;
int prime(int x){
    for(int f=2;f<x;f++){
        if(x%f==0){
            return 0;
        }
    }
    return 1;
}
int main(){
    int a;
    cin>>a;
    for(int i=2;i<a;i++){
        for(int j=2;j<a;j++){
            for(int k=2;k<a;k++){
                if((prime(i)&&prime(j)&&prime(k)) && (i+j+k)==a){
                    cout<<i<<" "<<j<<" "<<k<<" ";
                    return 0;
                }
            }
        }
    }

return 0;
}

by YY9999 @ 2024-12-10 16:40:33

可以只遍历两层利用i和j求出k,判断k是否为质数且是否大于0

#include<bits/stdc++.h>
using namespace std;
int prime(int x){
    if(x<=1) return 0;
    for(int f=2;f<x;f++){
        if(x%f==0){
            return 0;
        }
    }
    return 1;
}
int main(){
    int a;
    cin>>a;
    for(int i=2;i<a;i++){
        for(int j=2;j<a;j++){
            int k=a-i-j;
            if(prime(i)&&prime(j)&&prime(k)){
                cout<<i<<" "<<j<<" "<<k<<" ";
                return 0;
            }
        }
    }

    return 0;
}

by Lipearc @ 2024-12-11 21:49:56

good good thank you very much!


|