繁体   English   中英

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

[英]How to find the factors of a number given the prime factorization?

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

一种方法是将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]

您可以使用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}

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

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]

我是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.]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM