我正在使用下面的代码寻找2500的素因子,但我的代码目前只打印2个,我不确定为什么会这样。
no = 2500
count = 0
# Finding factors of 2500
for i in range(1,no):
if no%i == 0:
# Now that the factors have been found, the prime factors will be determined
for x in range(1,no):
if i%x==0:
count = count + 1
"""Checking to see if the factor of 2500, itself only has two factor implying it is prime"""
if count == 2:
print i
由于
答案 0 :(得分:3)
使用sieve of eratosthenes首先生成素数列表:
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
def prime_factors(sieve,n):
p_f = []
for prime in sieve:
while n % prime == 0:
p_f.append(prime)
n /= prime
if n > 1:
p_f.append(n)
return p_f
sieve = sieve_of_eratosthenes(2500)
print prime_factors(sieve,2500)
答案 1 :(得分:1)
对不起,我真的不了解你的算法,但是如果你有兴趣找到一个数字的因子,你可以得到以下结果(根据你的算法):
no = 2500
factors = [i for i in range(1,no) if no % i == 0]
count = len(factors)
在此示例中,因子将包含以下列表:
[1, 2, 4, 5, 10, 20, 25, 50, 100, 125, 250, 500, 625, 1250]
特别是对于素数,计数将为1。
编辑:好的,所以我确实误解了这个问题。该列表仅包含分隔符而非主要因素...对不起,请注意混淆!
答案 2 :(得分:0)
您的计数变量只会是一次== 2.
n = 2500
prime_factors = []
for p in range(2,n):
if p*p > n: break
while n % p == 0:
prime_factors.append(p)
n /= p
if n > 1: prime_factors.append(n)
print prime_factors
你可以获得2500的素数因子作为列表。 如果你只使用2到2500之间的素数而不是范围(2,n),它会更快。 Wikipedia - Trial division