Rus*_*hal 4 python prime-factoring
我写了一个整数分解函数,但是在弄乱它之后,我意识到它有几个数字的问题......
>>> 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]
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题?
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
Run Code Online (Sandbox Code Playgroud)
修改如下:
def pFactors(n):
"""Finds the prime factors of 'n'"""
from math import sqrt
pFact, limit, check, num = [], int(sqrt(n)) + 1, 2, n
if n == 1: return [1]
for check in range(2, limit):
while num % check == 0:
pFact.append(check)
num /= check
if num > 1:
pFact.append(num)
return pFact
for i in range(1,1000):
print pFactors(i)
Run Code Online (Sandbox Code Playgroud)
虽然我喜欢你最初编写的代码,但有几点:
你不需要isPrime.原因是,除了num之外,范围内的任何素数也将是除以num的任何复合的最小除数,因此当你将这些素数分开时,你将阻止它们组成的复合被发现为后来在范围内的除数,只留下素数因子.
您不需要对数组进行排序,它已经按check顺序升序排序.
添加的while循环确保只要它们继续划分num,就可以正确找到重复因子.
您可以使用同余来过滤掉少于限制的所有数字中的2/3以检查为除数,您能看到如何吗?
上面结果的最后几行是:
[11, 89]
[2, 2, 5, 7, 7]
[3, 3, 109]
[2, 491]
[983]
[2, 2, 2, 3, 41]
[5, 197]
[2, 17, 29]
[3, 7, 47]
[2, 2, 13, 19]
[23, 43]
[2, 3, 3, 5, 11]
[991]
[2, 2, 2, 2, 2, 31]
[3, 331]
[2, 7, 71]
[5, 199]
[2, 2, 3, 83]
[997]
[2, 499]
[3, 3, 3, 37]
Run Code Online (Sandbox Code Playgroud)