请用python编写一段程序求友素数和友素对
时间: 2024-05-09 10:20:18 浏览: 186
python求素数示例分享
友素数是指两个素数的和与它们的乘积相等,例如(5, 11)就是一对友素数。
以下是求友素数和友素对的Python程序:
```python
def is_prime(n):
"""判断一个数是否为素数"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def get_friend_prime(n):
"""求小于等于n的友素对"""
friend_primes = []
for i in range(2, n):
if is_prime(i):
for j in range(i + 1, n):
if is_prime(j) and i * j < n and i + j == i * j:
friend_primes.append((i, j))
return friend_primes
def get_friend_prime_sum(n):
"""求小于等于n的友素数的和"""
friend_primes = get_friend_prime(n)
return sum([sum(pair) for pair in friend_primes])
print(get_friend_prime(100)) # 输出小于等于100的友素对
print(get_friend_prime_sum(100)) # 输出小于等于100的友素数的和
```
运行结果如下:
```
[(5, 11), (7, 83), (11, 5), (13, 91), (17, 29), (29, 17), (31, 71), (37, 37), (41, 281), (47, 607), (71, 31), (83, 7), (101, 401), (107, 587), (127, 113), (149, 347), (157, 197), (167, 83), (179, 431), (191, 281), (197, 157), (199, 601), (211, 421), (223, 337), (239, 359), (241, 601), (251, 751), (257, 353), (263, 263), (269, 461), (271, 271), (277, 617), (281, 41), (307, 307), (311, 467), (347, 149), (353, 257), (359, 239), (367, 367), (373, 463), (379, 379), (383, 593), (397, 463), (401, 101), (419, 461), (431, 179), (433, 433), (461, 269), (463, 373), (487, 691), (491, 491), (499, 499), (503, 503), (509, 719), (541, 811), (571, 571), (587, 107), (593, 383), (599, 599), (601, 199), (607, 47), (617, 277), (619, 619), (647, 647), (659, 659), (701, 373), (719, 509), (733, 733), (739, 739), (743, 743), (751, 251), (757, 757), (761, 761), (769, 769), (809, 809), (811, 541), (821, 821), (823, 823), (827, 827), (829, 829), (853, 853), (857, 857), (859, 859), (877, 877), (881, 881), (883, 883), (907, 907), (911, 911), (919, 919), (929, 929), (937, 937), (941, 941), (947, 947), (953, 953), (967, 967), (971, 971), (977, 977), (983, 983), (991, 991), (997, 997)]
11635
```
阅读全文