PAT_A1015#Reversible Primes

Source:

PAT A1015 Reversible Primes (20 分)

Description:

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 Nand 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

Keys:

  • 进制转换
  • 素数(Prime)

Attention:

  • int < 1e9 ~ 2^8-1, long < 1e18 ~ 2^16-1;
  • 1e5的十进制转换为二进制会超过int范围,进制转换和逆置一起进行的话就避免中间数超出范围的问题了;

Code:

 1 /*
 2 Data: 2019-05-12 21:32:05
 3 Problem: PAT_A1015#Reversible Primes
 4 AC: 18:26
 5 
 6 题目大意:
 7 给一整数N<1e5,进制D
 8 求N的D进制逆置后是否仍是素数
 9 */
10 #include<cstdio>
11 #include<string>
12 #include<algorithm>
13 using namespace std;
14 const int M=1e5+10;
15 
16 bool isPrime(int num)
17 {
18     if(num==0 || num==1)
19         return false;
20     for(int i=2; i*i<=num; i++)
21         if(num%i==0)
22             return false;
23     return true;
24 }
25 
26 int Reverse(int n, int d)
27 {
28     int ans=0;
29     while(n!=0)
30     {
31         ans *= d;
32         ans += (n%d);
33         n /= d;
34     }
35     return ans;
36 }
37 
38 int main()
39 {
40 #ifdef  ONLINE_JUDGE
41 #else
42     freopen("Test.txt", "r", stdin);
43 #endif // ONLINE_JUDGE
44 
45     int n,d;
46     while(scanf("%d",&n) && n>=0)
47     {
48         scanf("%d", &d);
49         if(isPrime(n) && isPrime(Reverse(n,d)))
50             printf("Yes\n");
51         else
52             printf("No\n");
53     }
54 
55     return 0;
56 }

 

posted @ 2019-05-12 22:00  林東雨  阅读(119)  评论(0编辑  收藏  举报