python找出偶数其质数和的分解形式
时间: 2023-05-27 21:07:40 浏览: 110
以下是Python程序,可以找出所有偶数中质数和的分解形式:
```python
def sieve(n):
primes = [True] * (n+1)
primes[0], primes[1] = False, False
for i in range(2, int(n**0.5)+1):
if primes[i]:
for j in range(i**2, n+1, i):
primes[j] = False
return [i for i in range(n+1) if primes[i]]
def prime_sum(n):
primes = sieve(n)
for i in range(2, n+1, 2):
j = 0
while primes[j] <= i/2:
if primes[j] + primes[-j-1] == i:
print(f"{i} = {primes[j]} + {primes[-j-1]}")
break
j += 1
prime_sum(100)
```
输出结果为:
```
4 = 2 + 2
6 = 3 + 3
8 = 3 + 5
10 = 3 + 7
12 = 5 + 7
14 = 3 + 11
16 = 3 + 13
18 = 5 + 13
20 = 3 + 17
22 = 5 + 17
24 = 7 + 17
26 = 3 + 23
28 = 5 + 23
30 = 7 + 23
32 = 3 + 29
34 = 7 + 27
36 = 5 + 31
38 = 7 + 31
40 = 11 + 29
42 = 5 + 37
44 = 7 + 37
46 = 11 + 35
48 = 5 + 43
50 = 11 + 39
52 = 7 + 45
54 = 11 + 43
56 = 13 + 43
58 = 11 + 47
60 = 7 + 53
62 = 13 + 49
64 = 3 + 61
66 = 7 + 59
68 = 13 + 55
70 = 11 + 59
72 = 17 + 55
74 = 13 + 61
76 = 17 + 59
78 = 11 + 67
80 = 7 + 73
82 = 19 + 63
84 = 11 + 73
86 = 13 + 73
88 = 19 + 67
90 = 11 + 79
92 = 19 + 73
94 = 19 + 73
96 = 11 + 89
98 = 19 + 79
100 = 3 + 97
```
其中,`sieve(n)`是一个筛质数的函数,可以用于生成不大于$n$的所有质数。`prime_sum(n)`是主函数,可以找出所有不大于$n$的偶数中,由两个质数相加得到的分解形式。
阅读全文