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 Input Specification: Output Specification: Sample Input: 题意:给出来两个数n和b,如果n是一个素数,并且在b进制下反转之后还是一个素数,那这个数n就是一个可逆素数,输出Yes,否则输出No。 解题思路:
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.
For each test case, print in one line Yes if N is a reversible prime with radix D, or No if not.
73 10
23 2
23 10
-2
Sample Output:
Yes
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):
if n <= 3:
return n > 1
if n%6 != 1 and n%6 != 5:
return False
for i in range(5,int(math.sqrt(n)),6):
if n%i==0 or n%(i+2)==0:
return False
return True
def reverse(n, b):
l = []
while n >= b:
a = n%b
n = n//b
l.append(a)
l.append(n)
l = l[::-1]
s = 0
for i in range(len(l)):
s += l[i]*(b**i)
return s
while 1:
l = list(map(int,input().split()))
if l[0]<0:
break
if isprime(l[0]) and isprime(reverse(l[0],l[1])):
print('Yes')
else:
print('No')