C++蒟蒻求助o(╥﹏╥)o

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

jgngm @ 2024-03-12 13:43:10

#include<bits/stdc++.h>
using namespace std;
char n[100000000] ;
bool ZhiShu(int a){
    if (a < 2){
        return false ;
    }
    int len = sqrt(a);
    for (int i = 2 ; i <= len; ++i){
        if (a % i == 0){
            return false ;
        }
    }
    return true;
}
bool huiwen(int x)
{
    int len =  0 ;
    sprintf(n , "%d" , x);
    len = strlen(n);
    for (int i = 0 , j = len - 1 ; i < j ; ++i , --j){
        if (n[i] != n[j]){
            return false;
        }
    }
    return true;
} 
int main(){
    int n , m ;
    scanf("%d%d" , &n , &m);
    for (int i = n ; i <= m && i <= 9989899; ++i){
        if (ZhiShu(i)&&huiwen(i)){
            printf("%d\n" , i);
        }
    }
    return 0 ;
}

by jgngm @ 2024-03-12 13:43:42

3个TLEo(╥﹏╥)o


by c52_hdzyl @ 2024-03-12 14:47:08

@jgngm

#include<bits/stdc++.h>
using namespace std;
char n[100000000] ;
bool ZhiShu(int a){
    if(a==1)return 0;
    int len = sqrt(a);
    for (int i = 2 ; i <= len; ++i){
        if (a % i == 0){
            return false ;
        }
    }
    return true;
}
bool huiwen(int x){
//  int len =  0 ;
//  sprintf(n , "%d" , x);
//  len = strlen(n);
//  for (int i = 0 , j = len - 1 ; i < j ; ++i , --j){
//      if (n[i] != n[j]){
//          return false;
//      }
//  }
    int t=x,cnt=0;
    while(t!=0){
        cnt=cnt*10+t%10;
        t/=10;
    }
    if(cnt==x)return 1;
    return 0;
} 
int main(){
    int n , m ;
    scanf("%d%d" , &n , &m);
    for (int i = n ; i <= m && i <= 9989899; ++i){
        if (huiwen(i)&&ZhiShu(i)){
            printf("%d\n" , i);
        }
    }
    return 0 ;
}

你的回文有问题,可以不用用字符串做,直接模拟一边就好了。


by c52_hdzyl @ 2024-03-12 14:48:05

还有就是,要先判回文再判质数


by jgngm @ 2024-03-14 21:16:45

@c52_hdzyl 谢谢大佬ღ( ´・ᴗ・` )比心


|