2.3编写一个函数,判断一个正整数(大于3的正整数)是否是素数,是素数返回1,不是素数返回0。并编写一个简单的程序测试该函数的正确性
时间: 2023-07-15 12:13:51 浏览: 212
以下是判断一个正整数是否是素数的函数:
```python
def is_prime(n):
if n <= 3:
return n == 2 or n == 3
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
```
该函数采用了著名的 Miller-Rabin 算法,时间复杂度为 O(𝑘log3𝑛),其中 𝑘 是算法迭代次数,一般取 𝑘=20。
以下是一个简单的程序,测试该函数的正确性:
```python
for i in range(4, 21):
if is_prime(i):
print(i, 'is prime')
else:
print(i, 'is not prime')
```
输出结果为:
```
4 is not prime
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime
11 is prime
12 is not prime
13 is prime
14 is not prime
15 is not prime
16 is not prime
17 is prime
18 is not prime
19 is prime
20 is not prime
```
阅读全文