python求孪生素数

所谓孪生素数,是指两个差值为2的素数,如(3, 5)、(5, 7)、(11, 13),输入n,输出n以内的所有孪生素数对,要求孪生素数对以元组形式存放,所有元组存放在一个列表中。如:

n=20

[(3,5),(5,7),(11,13),(17,19)]

要求:输入输出风格与上述完全一致,但具体输入可以不同。

from math import sqrt

n = int(input("please enter N: "))

def isPrime(m):
    r = int(sqrt(m))
    for i in range(2, r + 1):
        if m % i == 0:
            return False
    return True

twin = []

for i in range(2, n + 1):
    t = i + 2
    if isPrime(i) and t <= n and isPrime(t):
        twin.append((i, t))

print(twin)

# Output
please enter N: 20
[(3, 5), (5, 7), (11, 13), (17, 19)]