最后3点超时啊!求解

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

dingjingxuan1234 @ 2024-10-25 19:09:32

#include <bits/stdc++.h>
using namespace std;
bool zhishu(int zs){
    for(int i=2;i<=sqrt(zs);i++){
        if(zs%i==0){
            return 0;
        }
    }
    if(zs>1){
        return 1;
    }
}
bool huiwenshu(int hws){
    int h=0,y=hws;
    while(hws){
        h=h*10+hws%10;
        hws=hws/10;
    }
    if(h==y){
        h=0;
        return 1;
    }
    h=0;
    return 0;
}
int main(){
    int a,b;
    cin>>a>>b;
    for(int j=a;j<=b;j++){
        if(zhishu(j)==1&&huiwenshu(j)==1){
            cout<<j<<"\n";
        }
    }
    return 0;
}

by BJqxszx_zhuyukun @ 2024-10-25 19:15:02

先判断回文再判断质数: if(huiwenshu(j)&&zhishu(j))


by BJqxszx_zhuyukun @ 2024-10-25 19:16:48

#include <bits/stdc++.h>
using namespace std;
bool zhishu(int zs){
    for(int i=2;i<=sqrt(zs);i++){
        if(zs%i==0){
            return 0;
        }
    }
    if(zs>1){
        return 1;
    }
}
bool huiwenshu(int hws){
    int h=0,y=hws;
    while(hws){
        h=h*10+hws%10;
        hws=hws/10;
    }
    if(h==y){
        h=0;
        return 1;
    }
    h=0;
    return 0;
}
int main(){
    int a,b;
    cin>>a>>b;
    if(a==2) printf("2\n");
    if(a%2==0) a++;
    for(int j=a;j<=b;j+=2){
        if(huiwenshu(j)==1&&zhishu(j)==1){
            printf("%d\n",j);
        }
    }
    return 0;
}

by dingjingxuan1234 @ 2024-10-25 19:40:22

感谢帮助!


by _d_h_f @ 2024-10-25 19:57:29

emm......也许可以尝试另外的算法是吧......


|