PAT 1015 Reversible Primes (20 分)————Python

题目
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 (<10
​5
​​ ) and D (1


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

题目大意
就是每行有两个数字,判断第一个数字和第一个数字按照第二个数字进行进制转换后的数字是否都是素数(质数),如果是的话,在对应的那一行输出Yes;否则,输出No。


解题思路

  • 就是定义两个函数,一个是判断素数的函数,另一个是进制转换的函数。
  • 然后分别判断输入的每一行数字。

作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:400 ms
内存限制:64 MB


Code

def identify(n):
    if n > 1:
        for j in range(2, n):
            if n % j == 0:
                return False
        else:
            return True
    else:
        return False
def change(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 True:
    l = list(map(int,input().split()))
    if l[0]<0:
        break
    if identify(l[0]) and identify(change(l[0],l[1])):
        print('Yes')
    else:
        print('No')

运行结果
PAT 1015 Reversible Primes (20 分)————Python_第1张图片

你可能感兴趣的:(PAT,python,算法)