编写程序,找出1000以内的所有孪生素数对。要求: 结果放在列表中 判断素数用函数实现
时间: 2023-06-19 22:04:41 浏览: 117
下面是Python代码实现:
```python
# 定义判断素数的函数
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# 查找孪生素数对
twins = []
for i in range(2, 1001):
if is_prime(i) and is_prime(i + 2):
twins.append((i, i+2))
print(twins)
```
输出结果为:
```
[(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61), (71, 73), (101, 103), (107, 109), (137, 139), (149, 151), (179, 181), (191, 193), (197, 199), (227, 229), (239, 241), (269, 271), (281, 283), (311, 313), (347, 349), (419, 421), (431, 433), (461, 463), (521, 523), (569, 571), (599, 601), (617, 619), (641, 643), (659, 661), (809, 811), (821, 823), (827, 829), (857, 859), (881, 883)]
```
阅读全文