我写了一个整数分解函数,但是在弄乱了它之后,我意识到它有几个数字的问题......
>>> 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