给定一个 N
,我试图找到每个正整数 a
和 b
,使得 N = a*b
。
我开始使用 sympy.ntheory.factorint
分解为质因数,它给我一个字典因子 -> 指数。
我已经有了这段代码,但我不想获得重复项(a
和 b
扮演相同的角色):
import itertools
from sympy.ntheory import factorint
def find_decompositions(n):
prime_factors = factorint(n)
cut_points = {f: [i for i in range(1+e)] for f, e in prime_factors.items()}
cuts = itertools.product(*cut_points.values())
decompositions = [((a := np.prod([f**e for f, e in zip(prime_factors, cut)])), n//a) for cut in cuts]
return decompositions
例子:
In [235]: find_decompositions(12)
Out[235]: [(1, 12), (3, 4), (2, 6), (6, 2), (4, 3), (12, 1)]
我想要得到的是:
Out[235]: [(1, 12), (3, 4), (2, 6)]
我试图通过使用范围扩展,如
e//2
,1 + e//2
,(1+e)//2
,1 + (1+e)//2
来减少cut_points
中的范围一半。但是这些方法都没有奏效。一个简单的解决方案显然是计算相同的结果并返回:
decompositions[:(len(decompositions)+1)//2]
但我正在寻找最终能减少计算次数的解决方案。