66分求助!3个TLE

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

CommonHat @ 2023-05-31 13:38:34

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

bool isprime(int n) {
    if(n<=1) return false;
    for(int i=2;i*i<=n;i++) {
        if(n%i==0) return false;
    }
    return true;
}

bool ispal(int n) {
    int pal=0;
    int k=n;
    while(k!=0) {
        pal=pal*10+k%10;
        k/=10;
    }
    if(pal==n) return true;
    else return false;
}

int main() {
    int n,m;
    cin>>n>>m;
    if(n%2==0) n++;
    for(int i=n;i<=m;i+=2) if((isprime(i)==1)&&(ispal(i)==1)) cout<<i<<endl;
    return 0;
}

by _colin1112_ @ 2023-05-31 13:44:40

@Alex_Rao 请学习:质数筛


by CommonHat @ 2023-05-31 14:05:10

@colin1112 明白了!感谢大神指路


|