22分,2AC4WA3TLE,求助C++

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

yzsy25071621 @ 2023-03-01 20:39:43

我这个除了超时外应该没错吧,怎么还有4WA呢

#include <algorithm>
#include <iostream>
#include <string>
#include <cmath>

using namespace std;

bool isPrime(int);
bool isSame(int);
int main()
{
    int a=0,b=0;
    cin>>a>>b;
    int mod=0;
    for(int i=a;i<=b;i+=2)
    {
        if(isPrime(i) && isSame(i))
        {
            cout<<i<<endl;
        }
    }
    return 0;
}

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

bool isSame(int m)
{
    string s1="",s2="";
    s1=s2=to_string(m);
    reverse(begin(s1),end(s1));
    return s1==s2;
}

by ZM____ML @ 2023-03-01 20:50:29

又来力,我先看看


by ZM____ML @ 2023-03-01 20:57:20

@yzsy25071621 先加一个特判

if(a%2==0) a++;

就可以6A3T


by yzsy25071621 @ 2023-03-01 21:00:57

@ZM____ML 代码里有啊

    for(int i=a;i<=b;i+=2)
    {
        if(isPrime(i) && isSame(i))
        {
            cout<<i<<endl;
        }
    }

by ZM____ML @ 2023-03-01 21:03:47

@yzsy25071621 上面特判是判断的偶数,因为偶数一定不会是回文质数


by yzsy25071621 @ 2023-03-01 21:07:09

@ZM____ML 多了一个WA...... 我屑屑你


by ZM____ML @ 2023-03-01 21:10:17

@yzsy25071621 我发现一个问题(


by yzsy25071621 @ 2023-03-01 21:12:10

@ZM____ML ?


by ZM____ML @ 2023-03-01 21:12:16

@yzsy25071621 原代码把

issame

改成

bool turn(int a){
    int t=a,x=0;
    while(t!=0){
        x=x*10+t%10;
        t=t/10;
    }
    if(x==a) return 1;
    return 0;
}

加上

if(b>=9999999) b=9999999;
if(a%2==0) a++;

两个特判

还有就是顺序改成

if(turn(i)&&isPrime(i))

如果是

isPrime(i)&&turn(i)

就会T


by yzsy25071621 @ 2023-03-01 21:15:18

@ZM____ML reverse()翻转字符串不行吗


by ZM____ML @ 2023-03-01 21:18:46

@yzsy25071621 # 7,#9会T


| 下一页