首页 > 其他 > 详细

PAT (Advanced Level) Practice 1015 Reversible Primes (20 分)

时间:2019-06-21 17:31:42      阅读:102      评论:0      收藏:0      [点我收藏+]

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

思路:先判断自身是否是素数,再转换为对应进制的数,再判断是否是素数。
 1 #include <iostream>
 2 #include <string.h>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <cstdio>
 6 #include <stack>
 7 using namespace std;
 8 int n,d;
 9 int _prime(int x)
10 {
11     if(x==1) return 0; 
12     int flag=1;
13     for(int i=2;i*i<=x;i++){
14         if(x%i==0){
15             flag=0;
16             break;
17         }
18     }
19     return flag;
20 }
21 int _deal(int n,int d)
22 {
23     stack<int> s;
24     while(n){
25         s.push(n%d);
26         n/=d;
27     }
28     int sum=0,t=1;
29     while(!s.empty()){
30         sum+=s.top()*t;
31         t*=d;
32         s.pop();
33     }
34     return sum;
35 }
36 int main()
37 {
38     while(cin>>n&&n>0){
39         cin>>d;
40         int flag;
41         if(!_prime(n)) flag=0;
42         else{
43             if(_prime(_deal(n,d))) flag=1;
44             else flag=0;
45         }
46         if(flag) cout<<"Yes"<<endl;
47         else cout<<"No"<<endl;
48     }
49     return 0;
50 }

 

PAT (Advanced Level) Practice 1015 Reversible Primes (20 分)

原文:https://www.cnblogs.com/shixinzei/p/11065673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!