超时!88分!请求帮助

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

_L_Z_Y_ @ 2024-03-20 12:36:53

#include<bits/stdc++.h>
using namespace std;
int summ=0;
bool cou(int x)
{
    for(int i=2;i*i<=x;i++)
    {
        if(x%i==0) return false;
    }
    return true;
}
bool co(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 false;
    return true;
} 
int main()
{
    int x,y;
    cin>>x>>y;
    for(int i=x;i<=y;i++)
    {
        if(co(i))
        {
            if(cou(i))
            {
                cout<<i<<endl;
            }
        }
    }
    return 0;
} 

by zhang_feng_rui @ 2024-03-20 12:55:19

r最大1e8,直接枚举肯定超时啊 @LZY109469


by zhang_feng_rui @ 2024-03-20 12:55:55

打错了,是b


by _Chjich_ @ 2024-03-20 13:01:11

@LZY109469 特判偶数

#include <bits/stdc++.h>
using namespace std;
long long x, y;

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

bool co(long long x) {
    long long a[20] = {0}, f = 1;
    while (x) {
        a[f] = x % 10, x /= 10, f++;
    }
    for (int i = 1; i <= f / 2; i++)
        if (a[i] != a[f - i])
            return false;
    return true;
}

int main() {
    cin >> x >> y;
    for (int i = x; i <= y; i++) {
        if (i % 2 == 0 && i != 2) {
            continue;
        }
        if (co(i) && cou(i)) {
            cout << i << endl;
        }
    }
    return 0;
}

求关


by jiangyunlong @ 2024-03-20 13:04:02

@LZY109469,实在不行,提交时用c++ 98 O2(


by _L_Z_Y_ @ 2024-03-20 13:24:29

@zhang_feng_rui 谢谢


by _L_Z_Y_ @ 2024-03-20 13:24:58

@C13408964921 已经OK了


by _L_Z_Y_ @ 2024-03-20 13:25:14

@jiangyunlong ok


|