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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值