簡體   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