在给定素数分解的情况下,如何找到数的因子?

时间:2019-05-30 01:56:18

标签: python

如果以[2, 2, 3, 5, 5]的形式给出数字的素因式分解,我将如何找到[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]形式的所有因子

我尝试通过迭代循环来完成此操作,但据我所知,它没有点击获取数字的方法,结果是两个以上的数字相乘

def find_factors(pfacts):
    pfacts = [1] + pfacts
    temp = []
    for i in pfacts:
        for j in pfacts[i+1:]:
            if i * j not in temp:
                temp.append(i * j)
    return [1] + temp

我知道这不是正确的方法,因为它只能发现少量因素

[1, 2, 3, 5, 6, 10, 15]

4 个答案:

答案 0 :(得分:2)

一种方法是将itertools.productnumpy.prodnumpy.power结合使用:

import numpy as np
from itertools import product

f = [2, 2, 3, 5, 5]
uniq_f = np.unique(f)
counts = np.array(list(product(*(range(f.count(i) + 1) for i in uniq_f))))
sorted(np.prod(np.power(uniq_f, counts), 1))

输出:

[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

答案 1 :(得分:0)

您可以使用itertools.combinations(将提供重复项)和set来过滤掉重复项:

from itertools import combinations
from functools import reduce
from operator import mul

factors = [2, 2, 3, 5, 5]

set(reduce(mul, combination) for i in range (1, len(factors) + 1) for combination in combinations(factors, i))

输出:

{2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300}

答案 2 :(得分:0)

将所有组合相乘并将它们添加到集合中。

import itertools

def multiplyList(myList):
    # Multiply elements one by one
    result = 1
    for x in myList:
        result = result * x
    return result

factors=set()

stuff = [2, 2, 3, 5, 5]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        factors.add(multiplyList(subset))

factors=list(sorted(factors))

print(factors)

其工作原理如下:

[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

答案 3 :(得分:0)

我是python的较新手,所以我很难理解已经发布的一些内容。这是我的答案,时间更长,但对于初学者来说可能更容易。

import numpy as np
import itertools

factors = [2, 2, 3, 5, 5]

al = []
for i in range(len(factors)):
    for combo in itertools.combinations(factors,i):
        al.append(np.prod(combo))

print(np.unique(al))

输出:

[  1.   2.   3.   4.   5.   6.  10.  12.  15.  20.  25.  30.  50.  60.
  75. 100. 150.]