求助,最后一个测试点TLE了

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

DreamGeorgeNotFound @ 2024-10-23 13:18:43

#include<bits/stdc++.h>
using namespace std;
int pd(int a)
{
    int i;
    for(i=2;i*i<=a;i++)
    if(a%i==0)return 0;
    return 1;
}
int mo(int a){
    int s1=0;
    int sd=a;
    while(sd!=0){
        s1=s1*10+sd%10;
        sd/=10;
    }
    if(s1==a){
        return 1;
    }else{
        return 0;
    }
}
int main(){

    int a,b;
    cin>>a>>b;
    int lzlzj=a;
    while(lzlzj<=b){
        if(mo(lzlzj)==1&&pd(lzlzj)==1){
            cout<<lzlzj<<endl;
        }
        lzlzj++;
    }

return 0;
}

酱紫,有什么优化的办法吗,本蒟蒻只会遍历,while貌似加的有点多


by wuxiaomi0103 @ 2024-10-23 13:46:50

参考下?

#include <bits/stdc++.h>
using namespace std;
bool cc(long long n){
    if(n==2){
        return 1;
    }
    if(n==1||n%2==0){
        return 0;
    }
    for(long long i=3;i<=sqrt(n);i+=2){
        if(n%i==0){
            return 0;
        }
    }
    return 1;
}
bool aa(int a){
    int n=a,m=0;
    while(n>0){
        m=m*10+n%10;
        n/=10;
    }
    if(a==m){
        return 1;
    }else{
        return 0;
    }
}
int main(){

    int a,b;
    cin>>a>>b;
    if(a%2==0){
        a++;
    }
    for(int i=a;i<=b;i+=2){
        if(aa(i)){
            if(cc(i)){
                cout<<i<<endl;
            }
        }
    }

    return 0;
}

by keep_eating @ 2024-10-23 13:53:06

// Problem: P1217 [USACO1.5] 回文质数 Prime Palindromes
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1217
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>

using namespace std;

#define endl '\n'

#define TRACE 1
#define tcout TRACE && cout

#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);

#define int long long
#define re register
#define inl inline
const int P = 998244353;
const int Base = 322225477;
const int INF = 0x3f3f3f3f3f3f3f3f;

const int N = 1e6 + 10, M = 2e3 + 10;
inl int pd(int a){
    int i;
    for(i=2;i*i<=a;i++)
    if(a%i==0)return 0;
    return 1;
}
inl int mo(int a){
    int s1=0;
    int sd=a;
    while(sd!=0){
        s1=s1*10+sd%10;
        sd/=10;
    }
    if(s1==a){
        return 1;
    }else{
        return 0;
    }
}
signed main() {
    fst
    int a,b;
    cin>>a>>b;
    int lzlzj=a;
    while(lzlzj<=b){
        if(mo(lzlzj)==1&&pd(lzlzj)==1){
            cout<<lzlzj<<endl;
        }
        lzlzj++;
    }
    return 0;
}


by DreamGeorgeNotFound @ 2024-10-23 13:54:00

@wuxiaomi0103 谢谢!


by DreamGeorgeNotFound @ 2024-10-23 13:54:18

@keep_eating 感谢


by __int1024 @ 2024-10-23 14:11:47

@keep_eating 可能需要多交几遍……


|