PAT 甲级 1015 Reversible Primes(20)

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 (<10​5​​) 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

Experiential Summing-up

判断输入是否为负数,判断n是否为素数,把n转换为d进制再反过来转换为10进制,判断是否为素数。

例如:23是素数,转换成2进制为11101,反转后为10111,转换成10进制数为29,还是素数,输出Yes

Accepted Code

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 bool isprime(int n)
 5 {
 6     if(n <= 1) return false;
 7     for(int i = 2; i <= n/2; i ++)
 8         if(n % i == 0)
 9             return false;
10     return true;
11 }
12 
13 int main()
14 {
15     int n, d;
16     while(scanf("%d", &n) != EOF)
17     {
18         if(n < 0) break;
19         cin >> d;
20         if(isprime(n) == false)
21         {
22             cout << "No" << endl;
23             continue;
24         }
25         int len = 0, arr[100];
26         do
27         {
28             arr[len++] = n % d;
29             n = n / d;
30         } while(n != 0);
31         for(int i = 0; i < len; i ++)
32             n = n * d + arr[i];
33         printf("%s", isprime(n) ? "Yes\n" : "No\n");
34     }
35     return 0;
36 }

 

posted @ 2023-04-18 21:29  爱吃虾滑  阅读(14)  评论(0编辑  收藏  举报