python素数判断
时间: 2023-11-20 21:58:54 浏览: 100
以下是Python中判断素数的五种实现方式:
1.暴力判断法
```python
def is_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
```
2.平方根暴力判断法
```python
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
```
3.素数表筛选法
```python
def get_primes(n):
primes = []
for i in range(2, n+1):
is_prime = True
for j in primes:
if i % j == 0:
is_prime = False
break
if is_prime:
primes.append(i)
return primes
```
4.埃拉托斯特尼(Eratosthenes)筛法
```python
def get_primes(n):
primes = [True] * (n+1)
primes[0] = primes[1] = False
for i in range(2, int(n**0.5)+1):
if primes[i]:
primes[i*i: n+1: i] = [False] * len(primes[i*i: n+1: i])
return [i for i in range(n+1) if primes[i]]
```
5.欧拉(Euler)筛法
```python
def get_primes(n):
primes = []
is_prime = [True] * (n+1)
for i in range(2, n+1):
if is_prime[i]:
primes.append(i)
for j in primes:
if i*j > n:
break
is_prime[i*j] = False
if i % j == 0:
break
return primes
```
阅读全文