答案运行正确但最后一点超时,求助,帮忙看下怎样优化

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

Xxxxyh @ 2024-10-26 10:08:02

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

int main()
{
    int a = 0, b = 0, i = 0, j = 0, m = 0, n = 0;

    scanf("%d %d", &a, &b);
    i = b - a + 1;
    int arr[i];

    for (i = a; i <= b; i++)
    {
        int u = i;
        int S = 0;
        //检验是否为回文数
        do
        {
            int num = u % 10;
            u /= 10;

            S = S + num;
            if (u)
            S *= 10;
        } while (u);

        if (S == i)           //存储回文数
        {
            arr[j] = S;
            j++;
        }

        //判断是否为质数

    }
    for (m = 0; m <= j - 1; m++)
    {
        int flag = 1;
        for (n = 2; n <= sqrt(arr[m]); n++)
        {
            if (arr[m] % n == 0)
            {
               flag = 0;           //若不为质数,操作终止,进入下次循环
               break;
            }
        }
        if (flag == 1)
        {
            printf("%d\n", arr[m]);
        }
    }
    return 0;
}

by laoniubi @ 2024-10-26 10:35:44

听取蛙声一片


by Xxxxyh @ 2024-10-26 17:29:44

@laoniubi ?


by zhkkk_ @ 2024-10-29 21:37:51

只要不大于O(n)就行


|