66分求大佬援助!!!

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

jiangyixuan_eason @ 2024-08-29 13:07:10

#include<bits/stdc++.h>
using namespace std;

bool isPrime(int n){
    bool x=true;
    for(int i=2;i<n;i++){
        if(n%i==0){
            x=false;
            break;
        }
    }
    return x;
}
bool palindromes(int n){
    string s1=to_string(n);
    string s2=to_string(n);
    reverse(s1.begin(),s1.end());
    if(s1 == s2){
        return true;
    }
    return false;
    int j=s1.size();
    int m=n%10*pow(10,j-1);
    for(int i=1;i<j;i++){
        int t=pow(10,i);
        m+=n/t%10*pow(10,j-1-i);
    }
    if(m==n){
        return true;
    }
    else{
        return false;
    }
}
int main(){
    int a,b;
    cin >>a>>b;
    for(int i=a;i<=b;i++){
        if(isPrime(i)){
            if(palindromes(i)){
            cout <<i<<endl;
            }
        }
    }
    return 0;
}

by jiangyixuan_eason @ 2024-08-29 13:15:25

谢谢,但是这样改完只有第1、2、3个点AC,剩下的全部TLE,这怎么优化呀?


by chengjindong @ 2024-08-29 13:16:45

if(isPrime(i))加上 i%2==1

@eason_jiang


by chengjindong @ 2024-08-29 13:19:31

改成if(i%2==1&&isPrime(i))


by jiangyixuan_eason @ 2024-08-29 13:20:40

可改完之后好像还是哪些点超时,是我写的逻辑有问题么? @chengjindong


by chengjindong @ 2024-08-29 13:22:19

endl改成'\n'试试


by chengjindong @ 2024-08-29 13:25:07

for(int i=2;i<n;i++)改成for(int i=2;i*i<=n;i++)


by chengjindong @ 2024-08-29 13:26:32

先判断palindromes(i)


by chengjindong @ 2024-08-29 13:27:41

A了

#include<bits/stdc++.h>
using namespace std;
bool isPrime(int n){
    bool x=true;
    for(int i=2;i*i<=n;i++){
        if(n%i==0){
            x=false;
            break;
        }
    }
    return x;
}
bool palindromes(int n){
    int m=0,t=n;
    while(t){
        m=m*10+t%10;
        t/=10;
    }
    return n==m;
}
int main(){
    int a,b;
    cin >>a>>b;
    for(int i=a;i<=b;i++){
        if(i%2==1&&palindromes(i)&&isPrime(i) ){
            cout <<i<<'\n';
        }
    }
    return 0;
}

by jiangyixuan_eason @ 2024-08-29 13:33:43

谢谢大佬,终于过了,AC已关


by chengjindong @ 2024-08-29 13:34:33

@eason_jiang 求关


| 下一页