PAT 1015.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 (< 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

我的解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cmath>

//解题思路:
//本题并没有什么难点,关键是对于题意的理解,这个radix表示基数
//一个数的reverse版本即为它的radix进制表示反转后再转换为10进制的值
//如:输入23, 2;
//23为素数,它的reverse版本为:
//23->(2进制表示)10111->(反转)11101->(10进制)29
//29也为素数,故输出Yes

using namespace std;

//判断是否素数
bool isPrime(int num)
{
if (num < 2) {
return false;
}

for (int i = 2; i < floor(sqrt(num) + 1); ++i) {
if (num % i == 0) {
return false;
}
}

return true;
}

//10进制数num的reverse版本
int reverse(int num, int radix)
{
int result = 0;

//num每次对radix取余恰好是其radix进制的反转表示
//此时顺便计算出其十进制值即可
while (num) {
result = result * radix + num % radix;
num /= radix;
}

return result;
}

int main()
{
int n, d;

while (cin >> n) {
if (n < 0) {
break;
}
cin >> d;
cout << (isPrime(n) && isPrime(reverse(n, d)) ? "Yes" : "No") << endl;
}

return 0;
}
Author: sphc
Link: https://jkuvw.xyz/archives/e4468b19/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
微信打赏
支付宝打赏