只需使用for循环,从prime\u gen获取素数列表:
def prime_gen(upper_limit):
prime_numbers = [2]
for i in range(3, upper_limit,2):
for j in range(2, i):
if i % j == 0:
break
else:
prime_numbers.append(i)
return prime_numbers
def prime_factors(n):
p_f = []
for prime in prime_gen(n):
# while n is divisible keep adding the prime
while n % prime == 0:
p_f.append(prime)
# update n by dividing by the prime
n //= prime
if n > 1:
p_f.append(n)
return p_f
print(prime_factors(40))
[2, 2, 2, 5] # -> 2*2*2*5
以40岁为例:
^{pr2}$
如果要快速生成素数,可以使用sieve:
from math import sqrt
def sieve_of_eratosthenes(n):
primes = range(3, n + 1, 2) # primes above 2 must be odd so start at three and increase by 2
for base in xrange(len(primes)):
if primes[base] is None:
continue
if primes[base] >= sqrt(n): # stop at sqrt of n
break
for i in xrange(base + (base + 1) * primes[base], len(primes), primes[base]):
primes[i] = None
primes.insert(0,2)
sieve=filter(None, primes)
return sieve