题解 | #素数回文#

素数回文

https://www.nowcoder.com/practice/d638855898fb4d22bc0ae9314fed956f

#include <cmath>
#include <iostream>
using namespace std;
bool isprime(long x) {
    if (x < 2) return false;
    if (x > 1 && x < 4) return true;
    for (int i = 2; i <= sqrt(x); i++) {
        if (x % i == 0) return false;
    }
    return true;
}
long outputnum(long x) {
    long n = x , temp = 0;
    int  count1 = 0, count2 = 0;
    while (n) {
        temp = n % 10;
        n /= 10;
        count2++;
    }
    n = x, temp = 0;
    for (int i = 0; i < count2; i++) {
        temp += (n % 10) * pow(10, count2 - i - 1);
        n /= 10;
    }
    for (int i = 1; i <= count2; i++) {				//消除与位数相同的数,以确保求出的回文是最小回文
        int b = x % ((int)(pow(10, i))) / pow(10, i - 1), c = temp / ((int)(pow(10,
                count2 - i))) / pow(10, i - 1);
        if (b == c && b == x % (int)(pow(10, 1))) count1++;
        else break;
    }
    x = x * pow(10, count2 - count1) + temp % (int)(1 * pow(10, count2 - count1));
    return x;
}
int main() {
    long a;
    cin >> a;
    if(!isprime(a)) return 0;
    if(isprime(outputnum(a))) cout <<"prime" << endl;
    else cout <<"noprime" << endl;
    return 0;

}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务