超时,求各位大佬优化

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

moranlxj @ 2024-10-29 23:00:22

#include<stdio.h>
#include<math.h>
#include<stdbool.h>
bool Prime(int n){
    int i;
    int cnt=0;
    for(i = 2;i<=pow(n,0.5);i++){
        if(n%i==0){
            cnt++;
        }
        if(cnt == 1){
            break;
        }
    }
    return cnt == 0;
} 

bool huiwen(int n){
    int start = n;
    int i;
    int res=0;
    while(n>0){
        i = n%10;
        res=res*10+i;
        n/=10;
    }
    return start == res;
}

int main(){
    int a,b;
    int n;
    scanf("%d%d",&a,&b);
    for(n = a;n<=b;n++){
        if(Prime(n)&&huiwen(n)){
            printf("%d\n",n);
        }
    }
}

by LionBlaze @ 2024-10-29 23:18:34

@moranlxj 枚举所有的回文数,挨个判断是否是质数。


by LionBlaze @ 2024-10-29 23:18:54

@moranlxj 枚举回文数的方法应该不用我说了,自行查看题面。


by moranlxj @ 2024-10-30 21:21:54

@LionBlaze okok 试了,谢谢


|