PAT甲级1015 Reversible Primes

素数判断+进制转换。

由于有多个 case,素数判断可以写个筛法。进制转换前面几题也有出现过,不多说了。

翻转字符串,对于 char[],可以用 strrev(s);对于 string,可以用 reverse(s.begin(), s.end())。当然,自己写也 ok。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
int n, d;
int primeList[maxn], cnt;
bool isPrime[maxn];

void eular() {
    memset(isPrime, true, sizeof(isPrime));
    isPrime[0] = isPrime[1] = false;

    for (int i = 2; i <= maxn; ++i) {
        if (isPrime[i]) primeList[++cnt] = i;
        for (int j = 1; j <= cnt && i*primeList[j] <= maxn; ++j) {
            isPrime[i*primeList[j]] = false;
            if (i % primeList[j] == 0) break;
        }
    }
}

int x2dec(string x, int radix) {
    int decx = 0;
    for (int i = 0; i < x.length(); ++i) {
        decx *= radix;
        decx += x[i]-'0';
    }
    return decx;
}

string dec2x(int d, int radix) {
    string x;
    while (d) {
        x = (char)(d%radix + '0') + x;
        d /= radix;
    }
    return x;
}

void solve() {
    while (cin >> n) {
        if (n < 0) break;

        cin >> d;
        string dn = dec2x(n, d);
        reverse(dn.begin(), dn.end());
        int rn = x2dec(dn, d);
        cout << (isPrime[n] && isPrime[rn] ? "Yes" : "No") << endl;
    }
}

int main() {
    eular();
    solve();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HNUCSEE_LJK/article/details/107876284