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 (<) and D (1), 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

 

题意:

  给出一个十进制数字N,将这个数字用D进制表示并反转后,问这个数字还是不是素数。

思路:

  字符串 + 模拟。

Code:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 bool isPrime(int n) {
 6     if (n == 1) return false;
 7     for (int i = 2; i * i <= n; ++i) {
 8         if (n % i == 0) {
 9             return false;
10         }
11     }
12     return true;
13 }
14 
15 int main() {
16     int n, d;
17     cin >> n;
18     while (n > 0) {
19         cin >> d;
20         string temp = "";
21         int r = n;
22         while (r > 0) {
23             temp += to_string(r % d);
24             r /= d;
25         }
26         int index = 0;
27         for (int i = temp.size() - 1; i >= 0; --i)
28             r += (temp[i] - '0') * pow(d, index++);
29         if (isPrime(n) && isPrime(r)) {
30             cout << "Yes" << endl;
31         } else {
32             cout << "No" << endl;
33         }
34         cin >> n;
35     }
36 
37     return 0;
38 }

 

上一篇:ARC111 B - Reversible Cards(思维+树的判断)


下一篇:PAT甲级 1015 Reversible Primes 进制转化+反转+判断素数