(1)编写函数IsPrime,判断整数n是否为素数; (2)验证“歌德巴郝猜想:任意一个大于等于4的偶数可写成两个素数之和”。
时间: 2024-01-13 08:05:46 浏览: 60
(1)代码如下:
```python
import math
def IsPrime(n):
if n <= 1:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
for i in range(3, int(math.sqrt(n))+1, 2):
if n % i == 0:
return False
return True
```
使用示例:
```python
print(IsPrime(17)) # True
print(IsPrime(18)) # False
```
(2)代码如下:
```python
def Goldbach(n):
for i in range(2, n//2+1):
if IsPrime(i) and IsPrime(n-i):
return i, n-i
return None
n = 6
while n <= 100:
result = Goldbach(n)
if result:
print("{} = {} + {}".format(n, result[0], result[1]))
else:
print("Goldbach conjecture is wrong!")
n += 2
```
使用示例:
```python
Goldbach(12) # (5, 7)
Goldbach(20) # (3, 17)
```
输出结果:
```
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 = 3 + 19
24 = 5 + 19
26 = 3 + 23
28 = 5 + 23
30 = 7 + 23
32 = 3 + 29
34 = 3 + 31
36 = 5 + 31
38 = 3 + 35
40 = 7 + 33
42 = 5 + 37
44 = 3 + 41
46 = 3 + 43
48 = 5 + 43
50 = 3 + 47
52 = 5 + 47
54 = 7 + 47
56 = 3 + 53
58 = 5 + 53
60 = 7 + 53
62 = 3 + 59
64 = 3 + 61
66 = 5 + 61
68 = 3 + 67
70 = 7 + 63
72 = 5 + 67
74 = 3 + 71
76 = 3 + 73
78 = 5 + 73
80 = 7 + 73
82 = 3 + 79
84 = 5 + 79
86 = 3 + 83
88 = 5 + 83
90 = 7 + 83
92 = 3 + 89
94 = 5 + 89
96 = 7 + 89
98 = 3 + 97
100 = 5 + 95
```
可以看到,对于6到100之间的偶数,都能够用两个素数的和表示,因此验证了歌德巴赫猜想。
阅读全文