I need 大佬们的help,为什么最后一个点还是tle

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

zuijiubugui @ 2024-01-03 20:07:47


int zshu(int x)
{
    int i;
    for(i=2;i<=sqrt(x);i++)
    {
        if(x%i==0) return 0;
    }
    return x;
}
int main()
{
    int i,len,j,m,n,count;
    char str[100];
    cin>>m>>n;
    if(m%2==0) m++;
    for(i=m;i<n+1;i+=2)
    {
        sprintf(str,"%d",i);
        len=strlen(str);
        if(len%2==0&&i!=11) continue;
        count=0;
        for(j=0;j<len/2;j++)
        {
            if(str[j]==str[len-j-1]) count++;//continue;只是跳过了本次循环 
        }
        if(count==len/2)
        {
            if(zshu(i)!=0) cout<<i<<endl;//比printf快10ms左右 
        }
    }
    return 0;
}

by GXZJQ @ 2024-01-03 20:28:55

@zuijiubugui 虽说不知道为什么 , 但还是提供一下我的代码 :

#include<bits/stdc++.h>
using namespace std;
int l, r;
bool weishu(int x)//位数
{
    if((1000 <= x && x <= 9999) || (100000 <= x && x <= 999999)) return 0; 
    return 1;
} 
bool huiwen(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 0; 
    return 1;
} 
bool zhishu(int x)//质数 
{
    if(x == 2) return 1;
    for(int i = 2; i <= sqrt(x); i++)
        if(x % i == 0) return 0;
    return 1;
}
int main()
{
    scanf("%d %d", &l, &r);
    if(l == 2) printf("2\n"); 
    if(l % 2 == 0) l++; 
    r = min(9999999, r);
    for(int i = l; i <= r; i = i + 2)
    {
        if(weishu(i) == 0) continue;
        if(huiwen(i) == 0) continue;
        if(zhishu(i) == 0) continue;
        printf("%d\n", i); 
    }   
    return 0;
}

by FiraCode @ 2024-01-03 20:31:15

@zuijiubugui 有没有一种可能这样做不太对(指时间复杂度


by FiraCode @ 2024-01-03 20:33:02

@zuijiubugui 还有就是用char比用int要慢


by OIerWu_829 @ 2024-01-03 20:44:01

@zuijiubugui

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

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 isPal(int x) // 回文数
{
    int m = 0;
    int t = x;
    while (t != 0)
    {
        int n = t % 10;
        t /= 10;
        m = m * 10 + n;
    }
    return m == x;
}

int main()
{
    int a, b;
    cin >> a >> b;
    if (b > 9999999) b = 9999999; // 特判
    for (int i = a; i <= b; i++)
    {
        if (isPal(i) && isPrime(i)) cout << i << endl;
    }
    return 0;
}

by zuijiubugui @ 2024-01-04 08:59:27

@FiraCode 谢谢【抱拳】


by zuijiubugui @ 2024-01-04 09:00:34

@GXZJQ ?


by zuijiubugui @ 2024-01-04 09:01:06

@wzj0829 ?


by zuijiubugui @ 2024-01-04 09:21:25

@zuijiubugui 这里统一回复(表情包在这里发出来乱码) 问题已经解决了 用字符慢很多 刚刚把回文判断用数字的方法换了一下 直接就通过了 同时感谢各位大佬!


by songyikang @ 2024-01-16 21:39:44

@wzj0829
if (b > 9999999) b = 9999999; // 特判佬,你这一步意思是针对测试点写的吗,如果给输入a=5,b=99999999是不是会超时啊


|