码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1015. Reversible Primes

时间:2015-02-21 09:42:17      阅读:195      评论: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 (< 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

思路:此题有教训 ,一个是判断素数的时候要<=sqrt 另外一个需要注意的是在反转的时候也可能出现1所以判断素数的时候要注意<=1的情况,要将此情况写到函数中去。
技术分享
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 using namespace std;
 5 int str[200];
 6 bool Judge(int a)
 7 {
 8     if(a<=1)
 9       return false;
10     int sqr=(int)sqrt(1.0*a);
11     for(int i=2;i<=sqr;i++)   //此处有问题需要注意 
12     {
13         if(a%i==0)
14           return false;
15     }
16     return true;
17 }
18 //进制转换 
19 int Change(int a,int d)
20 {
21     int index=0;
22     while(a!=0)
23     {
24         int remain=a%d;
25         str[index++]=remain;
26         a=a/d; 
27     }
28     //转换为十进制 
29     int sum=0;
30     for(int i=0;i<index;i++)
31     {
32         sum=sum*d+str[i];
33     }
34     return sum;
35 }
36 int main(int argc, char *argv[])
37 {
38     int N,D;
39     while(scanf("%d",&N)!=EOF)
40     {
41         if(N<0)
42           break;
43         scanf("%d",&D);
44         if(!Judge(N))
45         {
46             printf("No\n");
47             continue;
48         }
49         int after=Change(N,D);
50         if(!Judge(after))
51         {
52             printf("No\n");
53             continue;
54         }
55         printf("Yes\n");
56     }
57     return 0;
58 }
View Code

 

PAT1015. Reversible Primes

标签:

原文地址:http://www.cnblogs.com/GoFly/p/4296839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!