萌新求助 为什么后3个点超时了?

P1217 [USACO1.5] 回文质数 Prime Palindromes

yhnyyds @ 2022-10-29 11:21:24

这里是代码

#include <bits/stdc++.h>

using namespace std;

bool prime(int n) {
    if (n <= 1) return false;
    else {
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }
}

int huiwen(int num) {
    int sum = 0;
    while(num > 0) {
        sum = sum * 10 + num % 10;
        num /= 10;
    }
    return sum;
}

int main() {
    int n, m;
    cin >> n >> m;
    for (int i = n; i <= m; i++) {
        if (prime(i) && huiwen(i) == i) cout << i << endl;
    }

    return 0;
}

by lol_qwq @ 2022-10-29 12:08:39

@yhnyyds 可以不算8的数,因为8位的回文数都会被11整除,这样时间就降到了原来的十分之一


by SaintRelief @ 2022-10-29 12:09:52

一亿你这代码一定超时


by SaintRelief @ 2022-10-29 12:15:10

#include<bits/stdc++.h>
using namespace std;
int zh(int n){
    if(n<2) return 0;
    for(int i=2;i*i<=n;i++)
        if(n%i==0) return 0;
    return 1;
}
int main(){
    int a,b;
    cin>>a>>b;
    for(int i=a;i<=b&&i<=9989899;i++)
    {
        int t=i,m=0;
        for(;t;t/=10)
            m=m*10+t%10;
        if(i==m&&zh(i)==1) cout<<i<<endl;
    }
    return 0;
}

by SaintRelief @ 2022-10-29 12:15:43

我用这套代码过的


by SaintRelief @ 2022-10-29 12:18:23

9989899后面的你可以不列举


by yhnyyds @ 2022-10-29 12:21:43

谢大佬 此贴结


by yaohao123 @ 2022-10-29 18:39:49

@LDH123 谢谢大佬


by SaintRelief @ 2022-10-29 18:46:43

@yhnyyds你过了吗?


|