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 (<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
题意:给出来两个数n和b,如果n是一个素数,并且在b进制下反转之后还是一个素数,那这个数n就是一个可逆素数,输出Yes,否则输出No。
解题思路:
1.构造2个函数,isprime(n)用来判断n是否为素数,reverse(n, b)用来将n在b进制下反转并转回十进制。
2.判断素数的方法参考PAT 1152 Google Recruitment python解法。
3.reverse(n, b)中就是正常的除和取余获得n的b进制数,反转之后再乘起来变成十进制。
4.最后注意此题的循环结束条件是输入负数时结束循环,没有在最开始给出输入几行数据。
import math
def isprime(n):