60pts 壶关

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

DengWenZhangQwQ @ 2024-10-06 11:23:39


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

const int N=1e5;
int cnt=0;

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

}

bool romic(long long x)
{
    if(x<0)return false;
    long long reversed=0,original=x;

    while(x>0)
    {
        reversed=reversed*10+x%10;
        x/=10;
    }
    return reversed==original;
}

int main()
{
    int cm;
    long long a,b;
    cin>>a>>b;

    if(a%2==0)
    {
        cm=a+1;
    }
    else
    {
        cm=a;
    }

    for(long long i=cm;i<=b;i+=2)
    {
        if(isprime(i)&&romic(i))
        {
            cout<<i<<endl;
        }
    }

    return 0;
}

by ridewind2013 @ 2024-10-06 20:20:38

建议将质数判断改为埃筛: bool p[100000010]; void prime(int b) { memset(p,1,sizeof(p)); p[1]=0; int n=sqrt(b); for (int i=2;i<=n;i++) { if(p[i]) { for(int j=2;j<=b/i;j++)p[i*j]=0; } } }


by ridewind2013 @ 2024-10-06 20:22:35

然后在main函数里加if(b>=10000000)b=9999999;

再调用prime函数

判断是否为质数直接if(p[i])


by ridewind2013 @ 2024-10-06 20:27:19

bool p[100000010];
void prime(int b){ 
    memset(p,1,sizeof(p));
    p[1]=0;
    int n=sqrt(b);
    for(int i=2;i<=n;i++){ 
        if(p[i]){ 
            for(int j=2;j<=b/i;j++)p[i*j]=0; 
        } 
    } 
}

by ridewind2013 @ 2024-10-06 20:38:50

AC


by DengWenZhangQwQ @ 2024-11-17 09:17:44

@ridewind2013 我的神 包AC的


|