PTA 甲级 Reversible Primes (20 分)

题目链接

Reversible Primes

题目描述

 A reversible prime in any number system is a prime whose “reverse” in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a prime.
 Now given any two positive integers N (< 1 0 5 10^5 105) and D (1<D≤10), you are supposed to tell if N is a reversible prime with radix D.

个人想法:

 题目大意是:给出一个数,要求判断在指定 radix 下的表达方式翻转后根据该 radix 转换成为10进制是否为素数。

  • 给出数字是否为素数要判断
  • 0 和 1 不是素数

代码:

#include<iostream>
#include<algorithm>

using namespace std;

int cal(string n, int radix)
{
    int val = 0;
    for(auto t: n)
        val = val * radix + t - '0';
    return val;
}

string trans(int n, int radix){
    string res;
    while(n) {
        res = (char)(n % radix + '0') + res;
        n /= radix;
    }
    return res;
}

bool is_p(int x)
{
    if(x < 2) return false;
    for(int i = 2; i <= x / i; i++)
        if(x % i == 0) return false;
    return true;
}

string rev(string s)
{
    for(int i = 0, j = s.length() - 1; i <= j; i++, j--)
    {
        char t;
        t = s[i];
        s[i] = s[j];
        s[j] = t;
    }
    return s;
}

int main()
{
    int n, d;
    while(1) {
        scanf("%d", &n);
        if(n < 0) break;
        scanf("%d", &d);
        string str = trans(n, d);
        string re_str = rev(str);
        if(is_p(n) && is_p(cal(re_str, d))) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值