用Python写出1到30万以内的素数,请写出30中算法
时间: 2024-10-22 21:09:46 浏览: 46
在Python中,有多种方法可以找出1到30万之间的素数。以下是三种常见的算法:
1. **埃拉托斯特尼筛法**(Sieve of Eratosthenes):
```python
def sieve_of_eratosthenes(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*i, n+1, i):
primes[j] = False
return [i for i, is_prime in enumerate(primes) if is_prime]
print(sieve_of_eratosthenes(300000))
```
2. **暴力判断**(Brute Force):
```python
def brute_force_primes(n):
primes = []
for num in range(2, n+1):
is_prime = True
for divisor in range(2, num):
if num % divisor == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return primes
print(brute_force_primes(300000))
```
3. **米勒-拉宾素数检验**(Miller-Rabin Primality Test):
```python
from random import randint
def miller_rabin(n, k=5): # 经验值k=5已经足够准确
if n <= 1 or n == 4:
return False
if n <= 3:
return True
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
for _ in range(k):
a = randint(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1:
break
else:
return False
return True
primes = [num for num in range(2, 300001) if miller_rabin(num)]
print(primes[:30])
```
以上是三种不同的素数寻找策略,每种都有其优缺点和适用范围。其中埃拉托斯特尼筛法适用于查找较小范围内的素数,而暴力判断适合小规模且计算力允许的情况。米勒-拉宾则是更高效的随机化算法,用于大范围素数判断。
阅读全文