素因数分解関数を書いたのですが、いじってみると、いくつかの数値に問題があることに気づきました...
>>> 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