是否有算法可以找到整数的所有因子分解,最好是在Python / Java中,但欢迎任何反馈。
我有一个算法来计算素数因子。例如,[2,2,5]
是20
的主要因素。
def prime_factorization(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d)
n /= d
d += 1
if n > 1:
primfac.append(n)
return primfac
我还有一个算法来计算算法的所有因子(素数和非素数)。例如,20
的因素是[1, 2, 4, 5, 10, 20]
。
def factors(n):
a, r = 1, [1]
while a * a < n:
a += 1
if n % a: continue
b, f = 1, []
while n % a == 0:
n //= a
b *= a
f += [i * b for i in r]
r += f
if n > 1: r += [i * n for i in r]
return sorted(r)
我正在寻找的是一种返回给定整数的所有因子分解(而不是因子)的算法。对于整数20
,算法将生成以下内容:
[1,20]
[2,10]
[4,5]
[2,2,5]
谢谢!
答案 0 :(得分:3)
这是一种非常低效的方法。它会生成大量重复项,然后在返回之前将其过滤掉。
您的想法是从n=1
到len(factors)
包含因素进行选择,然后再重复使用未使用的因子。
import itertools
def mult(fs):
res = 1
for f in fs:
res *= f
return res
def _generate_all_factorizations(factors):
if len(factors) <= 1:
yield factors
return
for factors_in_mult in xrange(1, len(factors)+1):
for which_is in itertools.combinations(range(len(factors)), factors_in_mult):
this_mult = mult(factors[i] for i in which_is)
rest = [factors[i] for i in xrange(len(factors)) if i not in which_is]
for remaining in _generate_all_factorizations(rest):
yield [this_mult] + remaining
我添加了一个删除重复项的函数,并将它们排序很好地排序:
def generate_all_factorizations(factors):
seen = set()
res = []
for f in _generate_all_factorizations(factors):
f = tuple(sorted(f))
if f in seen:
continue
seen.add(f)
yield f
现在只需将它归结为主要因子化:
for factorization in generate_all_factorizations([2, 2, 5]):
print factorization
print "----"
for factorization in generate_all_factorizations([2, 3, 5, 7]):
print factorization
结果:
(2, 2, 5)
(2, 10)
(4, 5)
(20,)
----
(2, 3, 5, 7)
(2, 3, 35)
(2, 5, 21)
(2, 7, 15)
(2, 105)
(3, 5, 14)
(3, 7, 10)
(3, 70)
(5, 6, 7)
(5, 42)
(7, 30)
(6, 35)
(10, 21)
(14, 15)
(210,)
答案 1 :(得分:2)
您的任务是确定数字的multiplicative partition。谷歌应该指出你需要去的地方。 Stack Overflow已经有an answer。
答案 2 :(得分:1)
只是为了好玩:
from itertools import combinations_with_replacement
from operator import mul
my_integer = 20
factorizations = {t for t in {list(t).remove(1) if 1 in t and len(t)>2 else t if len(t)>1 else None for combo in [combinations_with_replacement(factors(my_integer), n) for n in xrange(len(factors(my_integer)))] for t in combo if reduce(mul, t, 1) == my_integer} if t}
print factorizations
set([(4, 5), (2, 2, 5), (1, 20), (2, 10)])