全部TLE,大佬救我!

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

littlewhite_ @ 2023-08-15 11:00:43

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

int dislocation(int x)
{
    int y = x;
    int cnt = 0;
    while (y >= 0)
    {
        y /= 10;
        cnt++;
    }
    return cnt;
}

bool is_palindrome(int n)
{
    int ans = 0;
    int res = n;
    for (int i = 1; i <= dislocation(n); i++)
    {
        ans = ans * 10 + n % 10;
        n /= 10;
    }
    if (ans == res)
    {
        return true;
    }
    else
    {
        return false;
    }
} 

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

int main()
{
    int a, b;
    cin >> a >> b;
    for (int i = a; i <= b; i++)
    {
        if (is_prime(i))
        {
            if (is_palindrome(i))
            {
                cout << i << endl;  
            }   
        }
    }
    return 0;
} 

救救救救救救救救救救救救!!!


by Field_Mouse @ 2023-08-15 11:11:15

@littewhite 这题暴力筛质数且一个一个判的话会t的很惨的


by pzx1234 @ 2023-08-15 11:11:15

mgmghmkkkykkykyukyukykuykuuykkyukyukk k yuk yku yk g yk ky k yk yk yk yk y kk yk y kuy kyu k uk yuk yuk yu kyu kyu ky k ku k uk yu kyu k uyk k k


by Field_Mouse @ 2023-08-15 11:11:34

@pzx1234 您?


by littlewhite_ @ 2023-08-15 11:13:44

@egg_rat 可我不知道怎么优化,可以示范一下吗?或者思路也行


by Leo_Longlong @ 2023-08-15 11:18:42

is_palindrome函数的第3行for循环中dislocation函数被重复计算了dislocation(n)次,消耗了很长时间


by Leo_Longlong @ 2023-08-15 11:20:54

建议将is_palindrome函数修改为:

bool is_palindrome(int n) {
    int ans = 0, cnt = 0, res = n;
    while (n >= 0) {
        n /= 10;
        cnt++;
    }
    n = res;
    for (int i = 1; i <= cnt; i++) {
        ans = ans * 10 + n % 10;
        n /= 10;
    }
    if (ans == res) {
        return 1;
    }
    return 0;
}

by Leo_Longlong @ 2023-08-15 11:24:07

is_prime函数中:

    if (x == 0)
    {
        return false;
    }
    if (x == 1)
    {
        return false;
    }

这8行代码是完全无用的,因为题目写了4<a,所以x不可能小于2


by littlewhite_ @ 2023-08-15 11:24:46

@Leo_Longlong 谢谢!


by Leo_Longlong @ 2023-08-15 11:29:40

dislocation函数完全可以嵌套进is_palindrome函数中,节省传参的时间:

bool is_palindrome(int n) {
    int ans = 0, cnt = 1, res = n;
    while (n > 0) {
        n /= 10;
        cnt++;
    }
    n = res;
    for (int i = 1; i <= cnt; i++) {
        ans = ans * 10 + n % 10;
        n /= 10;
    }
    if (ans == res) {
        return 1;
    }
    return 0;
}

把dislocation函数删掉再将is_palindrome函数换成这段代码即可


by Leo_Longlong @ 2023-08-15 11:30:02

不客气


| 下一页