66分大佬救救我!!#7#8#9测试点TLE了

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

woshishasan @ 2025-01-07 19:12:50

#include<bits/stdc++.h>
using namespace std;
int main(){
    int m,n,i,j,s=0,l=0;
    cin>>m>>n;
    if(m==1)
    {
        m++;
    }   
    for(i=m;i<=n;i++)
    {
        int l=0;
        for(j=2;j*j<=i;j++)
        {
            if(i%j==0)
            {
                l=1;
                break;
            }
        }
        int a=i,b=0;
        while(a!=0)
        {
            b=b*10+a%10;
            a=a/10;
        }
        if(i==b&&l==0)
        {
            cout<<i<<endl;
        }
    }

}

by wangxiangquan @ 2025-01-07 19:19:23

你把质数判断和回文数判断都写成函数就行。


by wangxiangquan @ 2025-01-07 19:20:28

#include <bits/stdc++.h>
using namespace std;
int a[110];
bool zhishu(int x)//质数判断
{
    for(int i=3;i<=sqrt(x);i++)
        if(x%i==0) return 0;
    return 1;
}
bool huiwen(int x)//回文数数判断
{
    int len;
    while(x!=0)
    {
        len++;
        a[len]=x%10;
        x/=10;
    }
    if(len==1)
    {
        a[len]=0;
        return 1;
    }
    for(int i=1;i<=len/2;i++)
        if(a[i]!=a[len-i+1]) return 0;
    for(int i=1;i<=len;i++) a[i]=0;
    return 1;
}
int main()
{

    int a,b;
    scanf("%ld%ld",&a,&b);
    if(b>9999999) b=9999999;
    if(a%2==0) a++;
    for(int i=a;i<=b;i+=2)
    {
        if(huiwen(i)==0) continue;
        if(zhishu(i)) printf("%ld\n",i);
    }
}

by woshishasan @ 2025-01-08 12:39:32

@wangxiangquan 已改 谢谢神犇(大佬)


|