80分,两个超过时间限制,请问大佬们如何优化

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

黎璃 @ 2020-02-12 16:53:17

#include <stdio.h>
#include <math.h>

int is_prime(int i);

int main() {
    int n, a, b, c;
    scanf("%d", &n);
    for(int i = 2; i < n; i ++ ) {
        if(is_prime(i)) {
            for(int j = 2; j < n; j ++) {
                if(is_prime(j)) {
                    for(int k = 2; k < n; k ++) {
                        if(is_prime(k)) {
                            if(i + j + k == n) {
                                printf("%d %d %d", i, j, k);
                                goto Flag;
                            }
                        }
                    }
                }
            }
        }
    }
    Flag: ;
    return 0;
}

int is_prime(int i) {
    if(i == 2) {
        return 1;
    }
    for(int j = 2; j <= fabs(sqrt(i)); j ++) {
        if(i % j == 0) {
            return 0;
        }
    }
    return 1;
}

by cmll02 @ 2020-02-12 17:00:06

for(int i = 2; i < n; i ++ ) {
        if(is_prime(i)) {
            for(int j = 2; j < n; j ++) {
                if(is_prime(j)) {
                    int k=n-i-j;
                        if(is_prime(k)) {
                                printf("%d %d %d", i, j, k);
                                goto Flag;
                            }
                        }
                    }
                }

    }

by wz441135118 @ 2020-02-12 17:14:03

帮你弄好了,不一定每次都要从2到n

https://www.luogu.com.cn/paste/lm6jhf2u


by 黎璃 @ 2020-02-13 18:21:51

@wz441135118 非常感谢


by 黎璃 @ 2020-02-13 18:39:16

@shygo_cmll02 非常感谢

但存在一点小问题,k需要满足k != 0 && k != 1

否则会产生错误,如999 ——> 2 997 0


by cmll02 @ 2020-02-13 19:09:49

我好菜啊


by 黎璃 @ 2020-02-13 19:19:43

@shygo_cmll02

您谦虚了

再次感谢你提供的思路


by herselfqwq @ 2020-10-03 12:25:46

最好枚举2个数字,第三个能算不举


|