如何在python中获取给定数量的因子的可能数字的列表?

问题描述 投票:0回答:3

我可以得到给定数量的因数和因数:

def all_factors(x):
    factors = []
    for i in range(1, x + 1):
        if x % i == 0:
            factors.append(i)
    return factors
print(all_factors(320))
print(len(all_factors(320)))

它提供以下输出:

[1、2、4、5、8、10、16、20、32、40、64、80、160、320]

14

但是,我该怎么做呢?例如:如果我的因子数= 4,则可能的列表必须为[6、10、14、21,...],在这里我们可以限制列表中的最大整数。

python factors
3个回答
1
投票

您可以使用:

def all_factors(x, number_factors):
    factors = []

    for i in range(1, x + 1):
        if len(factors) == number_factors:
            break 

        if x % i == 0:
            factors.append(i)
    return factors

0
投票

Code使用您的all_factors代码

def reverse_factors(n, max_):
  # Loops through numbers from 1 to max_ to check
  # and keeps the ones with desired number of factors
  # as determined by len(all_factors(x))
  return [x for x in range(1, max_+1) if len(all_factors(x))  == n]

Test

# Numbers with 4 factors up to 30
print(reverse_factors(4, 30))

输出

[6, 8, 10, 14, 15, 21, 22, 26, 27]

0
投票

尝试:

n =int(input("Enter the limit: "))
factno = int(input("No of factors: ")) # here 4
listing = []
for i in range(1,n+1):
    #Your code here to find factors and to add then to a list named "factors'
    factors = []
    for j in range(1, i + 1):
        if i % j == 0:
            factors.append(j)
    if len(factors) == factno:
        listing.append(i)
print(listing)
© www.soinside.com 2019 - 2024. All rights reserved.