最后一个超时了

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

Xingyi_2014 @ 2024-07-29 13:00:09

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,m,flag=1;
    cin>>n>>m;
    for(int k=n;k<=m;k++){
        int a=k,s=1,g,x=1;
        flag=1;
        while (a!=0){
            g=a%10;
            if(x==1){
                s=g;
            }
            else{
                s=s*10+g;
            }
            a=a/10;
            x++;
        }
        if(s==k)flag=1;
        else flag=0;
        if(flag==1){
            if(k==2)flag=1;
            else if(k<2 || k%2==0)flag=0;
            else{
                for(int j=3;j*j<=k;j+=2){
                    if(k%j==0){
                        flag=0;
                        break;
                    }
                }
            }
        }
    }
    for(int k=n;k<=m;k++){
        int a=k,s=1,g,x=1;
        flag=1;
        while (a!=0){
            g=a%10;
            if(x==1){
                s=g;
            }
            else{
                s=s*10+g;
            }
            a=a/10;
            x++;
        }
        if(s==k)flag=1;
        else flag=0;
        if(flag==1){
            if(k==2)flag=1;
            else if(k<2 || k%2==0)flag=0;
            else{
                for(int j=3;j<=sqrt(k);j+=2){
                    if(k%j==0){
                        flag=0;
                        break;
                    }
                }
            }
        }
        if(flag==1)cout<<k<<endl;
    }
    return 0;
} 

by haimingbei @ 2024-07-29 13:02:29

@Xingyi_2014

(AC,求关注)

代码:

#include<bits/stdc++.h>
using namespace std;
int a,b;
bool zs(int n){
    if(n==0||n==1)return 0;
    for(int i=2;i*i<=n;i++){
        if(n%i==0)return 0;
    }
    return 1;
}
int hws(int n){
    int a=n,s=0;
    while(a){
        s=s*10+a%10;
        a/=10;
    }
    return s;
}

int main(){
    cin>>a>>b;
    if(a%2==1){
        for(int i=a;i<=b;i+=2){
            if(i==hws(i)){
                if(zs(i)==1)cout<<i<<endl;
            }
        }
    }
    else {
        for(int i=a+1;i<=b;i+=2){
            if(i==hws(i)){
                if(zs(i)==1)cout<<i<<endl;
            }
        }
    }
    return 0;
}

by Oldragon @ 2024-07-29 13:02:58

特判偶数?(省去找偶数的时间)


by haimingbei @ 2024-07-29 13:04:40

我代码不就是判定奇偶数吗?


by Oldragon @ 2024-07-29 13:06:13

额我说楼主@haimingbei


by Xingyi_2014 @ 2024-07-30 13:51:39

谢谢


by Xingyi_2014 @ 2024-07-30 13:53:32

关注好了


|