三个超时66分求助

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

more_Power @ 2023-09-05 20:33:04

#include<iostream>
#include<string>
using namespace std;
int main()
{
    int a, b;
    cin >> a >> b;
    if (a % 2 != 0 || a==2)
    {
        for (int i = a; i <= b; i+=2)
        {
            string x = to_string(i);
            int length = x.size();
            int test = 0;
            for (int j = 0; j <= length / 2; j++)
            {
                if (int(x[j]) != int(x[length - 1 - j]))
                {
                    test = 1;
                    break;
                }
            }
            if (test == 0)
            {
                int testt = 0;
                for (int j = 2; j <= i / 2; j++)
                {
                    if (i%j == 0)
                    {
                        testt = 1;
                        break;
                    }
                }
                if (testt == 0)
                {
                    cout << i << endl;
                }
            }
        }
    }
    else
    {
        a = a + 1;
        for (int i = a; i <= b; i += 2)
        {
            string x = to_string(i);
            int length = x.size();
            int test = 0;
            for (int j = 0; j <= length / 2; j++)
            {
                if (int(x[j]) != int(x[length - 1 - j]))
                {
                    test = 1;
                    break;
                }
            }
            if (test == 0)
            {
                int testt = 0;
                for (int j = 2; j <= i / 2; j++)
                {
                    if (i%j == 0)
                    {
                        testt = 1;
                        break;
                    }
                }
                if (testt == 0)
                {
                    cout << i << endl;
                }
            }
        }
    }

    system("pause");
    return 0;
}

我觉得已经很节省了,还是有三个超时,求问QAQ


by Rieman_sum @ 2023-09-05 20:53:30

@KNNNNNN 加上这个判断函数:

bool check(int x)
{
    if(x>11&&x<100||x>999&&x<10000||x>99999&&x<1000000||x>9999999&&x<100000000)
    return false;
}

自己想想为什么


|