【发布时间】:2013-01-27 18:40:59
【问题描述】:
我写了一个整数分解函数,但在搞砸之后,我意识到它有几个数字的问题......
>>> pFactors(99) # it does work for numbers with multiple of one prime factor
[3, 3, 11]
>>> pFactors(999) # however, sometimes, it doesn't
[3, 37] # the actual prime factorization of 999 is [3, 3, 3, 37].
>>> pFactors(88)
[2, 11]
>>> pFactors(888)
[2, 3, 37]
我的代码有什么问题?
def pFactors(n):
"""Finds the prime factors of 'n'"""
from primes import isPrime
from math import sqrt
pFact, limit, check, num = [], int(round(sqrt(n), 2)) + 1, 2, n
if isPrime(n):
return [n]
for check in range(2, limit):
if isPrime(check) and num % check == 0:
pFact.append(check)
num /= check
if isPrime(num):
pFact.append(num)
break
pFact = sorted(pFact)
return pFact
【问题讨论】:
-
每次分解数字都需要重新计算
limit并重启循环。我会在这里推荐一种递归方法,而不是你的迭代方法。