求大佬解答如何修改这串代码(初学者)

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

Aiaoming @ 2024-12-12 14:30:42

#include<stdio.h>
#include<math.h>
int isPrime(int num)
{
    if(num<2)
    {
        return 0;
    }
    int limit=(int)sqrt(num)+1;
    for(int i=2;i<limit;i++)
    {
        if(num%i==0)
        {
            return 0;
        }
        return 1;
    }
}
int isPalindrome(int num)
{
    int original=num;
    int rev=0;
    while(num!=0)
    {
        int temp=num%10;
        num=num/10;
        rev=rev*10+temp;
    }
    return(original==rev);
}
int main()
{
    int a,b;
    scanf("%d %d",&a,&b);
    for(int i=a;i<=b;i++)
    {
        if(isPrime(i)&&isPalindrome(i))
        {
            printf("%d\n",i);
        }
    }
    return 0;
}

by do_it_tomorrow @ 2024-12-12 14:34:49

@Aiaoming 何不用手修改?


by EXR_FAL @ 2024-12-12 14:36:44

@do_it_tomorrow 胡说,应该用键盘改(雾


by Lipearc @ 2024-12-12 14:57:24

自己写的,但是TLE:

#include<bits/stdc++.h>
using namespace std;
int isprime(int x){
    for(int f=2;f<x;f++){
        if(x%f==0){
            return 0;
        }
    }
    return 1;
}

int rev(int x){
    int s=0;
    while(x){
        s=s*10+x%10;
        x/=10;
    }
    return s;
}

int main(){
    int a,b;
    cin>>a>>b;
    for(int i=a;i<=b;i++){
        if(isprime(i)){
            if(rev(i)==i){
                cout<<i<<endl;
            }
        }
    }

return 0;
}

by LionBlaze @ 2024-12-12 15:01:31

@zhexueder 胡说,得用计算机改啊


by LionBlaze @ 2024-12-12 15:01:54

@LionBlaze 胡说,肯定得用大脑或者小脑改!


by LiuSC_SZ @ 2024-12-17 20:38:28

用C++11,开启O2优化方可AC

#include <stdio.h>
#include <math.h>

int l,r;
bool check1(int x);
bool check2(int x);

int main() {
    scanf("%d %d", &l, &r);
    for(int i = l;i <= r;i++) {
        if(check1(i) == 0 || check2(i) == 0) {
            continue;
        }
        printf("%d\n",i);
    }   
    return 0;
}

bool check1(int x) {
    int a[20], flag = 1;
    while(x > 0) {
        a[flag] = x % 10;
        x /= 10;
        flag++;
    } 
    for (int i = 1;i <= flag / 2;i++){
        if(a[i] != a[flag-i]) return 0; 
    }

    return 1;
} 

bool check2(int x) {
    if(x == 2) return 1;
    for(int i = 2;i <= sqrt(x);i++) {
        if(x % i == 0) return 0;
    }   
    return 1;
}

|