用Python求25种不同的方法求素数,语法和算法不限,只要语法和算法有一个不同就行
时间: 2024-10-17 15:12:21 浏览: 20
算法领域python实现代码
在Python中,有多种方法可以找出素数。这里列举25种不同的方法示例,它们涵盖了不同的算法(如试除法、埃拉托斯特尼筛法、质因数分解等),以及语法上的变化:
1. **直接循环检查** (Brute Force):
```python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
for num in range(2, 26):
print(is_prime(num))
```
2. **埃拉托斯特尼筛法** (Sieve of Eratosthenes):
```python
def sieve_of_eratosthenes(n):
primes = [True] * (n+1)
primes[0], primes[1] = False, False
for p in range(2, int(n**0.5)+1):
if primes[p]:
for i in range(p*p, n+1, p):
primes[i] = False
return [i for i, prime in enumerate(primes) if prime]
sieve = sieve_of_eratosthenes(25)
print(sieve)
```
3. **质因数分解** (Factorization):
```python
def prime_factors(n):
factors = []
d = 2
while d * d <= n:
if n % d:
d += 1
else:
n //= d
factors.append(d)
if n > 1:
factors.append(n)
return factors, all(factor > 1 for factor in factors)
primes = [num for num in range(2, 26) if all(prime_factors(num)[0])]
print(primes)
```
4. **递归版本** (Recursive approach):
```python
def is_prime_recursive(n, i=2):
if n <= 2 or not i * i <= n:
return n == 2
if n % i == 0:
return False
return is_prime_recursive(n, i + 1)
prime_list = [num for num in range(2, 26) if is_prime_recursive(num)]
print(prime_list)
```
阅读全文