双素数是一对相差两个的素数。前两个素数为{3,5},{5,7},{11,13}和{17,19}。您可以通过运行for循环并检查数字的素数来在python中生成素生双胞胎。
def is_prime(n): for i in range(2, n): if n % i == 0: return False return True def generate_twins(start, end): for i in range(start, end): j = i + 2 if(is_prime(i) and is_prime(j)): print("{:d} and {:d}".format(i, j)) generate_twins(2, 100)
输出结果
这将给出输出-
3 and 5 5 and 7 11 and 13 17 and 19 29 and 31 41 and 43 59 and 61 71 and 73