PAT甲级(Advanced Level) Practice 1015 Reversible Primes

原题

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 (<105) and D (1<D≤10), you are supposed to tell if N is a reversible prime with radix D.

Input Specification:

The input file consists of several test cases. Each case occupies a line which contains two integers N and D. The input is finished by a negative N.

Output Specification:

For each test case, print in one line Yes if N is a reversible prime with radix D, or No if not.

Sample Input:

73 10
23 2
23 10
-2

Sample Output:

Yes
Yes
No

 题目翻译

在任何数制中,可逆质数是指在该数制中其 "f反转 "也是质数的质数。例如,在十进制中,73 是一个可逆质数,因为它的相反数 37 也是一个质数。

现在给定任意两个正整数 N (<105) 和 D (1<D≤10),你应该知道 N 是否是弧度为 D 的可逆质数。

输入规范:

输入文件由多个测试用例组成。每个案例占一行,包含两个整数 N 和 D。

输出说明:

对于每个测试用例,如果 N 是弧度为 D 的可逆质数,则在一行中打印 "Yes";如果不是,则打印 "No"。

解题思路

本题没什么难的,要注意的是1不是质数,否则测试点2过不了。

代码(c++)

 

#include <bits/stdc++.h>

using namespace std;

bool is_prime(int x){                                // 判断是否为质数
    if(x == 1) return false;
    
    for(int i = 2; i <= x / i; i++)
        if(x % i == 0) return false;
    return true;
}

int reverse(int x, int radix){                       // 反转
    string str = "";
    while(x != 0){                                   // 先转换为反转的radix进制,用str存储
        str = str + to_string(x % radix);
        x /= radix;
    }

    int res = 0, p = 1;
    for(int i = str.size() - 1; 0 <= i; i--) {       // 转换为10进制
        res += (str[i] - '0') * p;
        p *= radix;
    }
    
    return res;
}

int main(){
    int a, b;
    cin >> a;
    while(a > 0){
        cin >> b;
        if(is_prime(a) && is_prime(reverse(a, b))) printf("Yes\n");
        else printf("No\n");
        cin >> a;
    }
    
    return 0;
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值