[英]how to get list of possible numbers with given number of factors in python?
I can get the factors and number of factors of a given number:我可以得到给定数字的因子和因子数:
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)))
It gives the following output:它给出了以下 output:
[1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64, 80, 160, 320] [1、2、4、5、8、10、16、20、32、40、64、80、160、320]
14 14
But, how can I do the reverse of it?但是,我该如何做相反的事情呢? For example: If I have number of factors = 4, the possible list must be [6, 10, 14, 21, ...] where we can limit the maximum integer in the list.例如:如果我的因子数 = 4,则可能的列表必须是 [6, 10, 14, 21, ...] 我们可以限制列表中的最大 integer。
Try:尝试:
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)
you can use:您可以使用:
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
Code Using your all_factors code代码使用你的 all_factors 代码
def reverse_factors(n, max_):
# Loops through numbers from 1 to max_ to check
# number of factors. Keeps the ones with the 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))
Output Output
[6, 8, 10, 14, 15, 21, 22, 26, 27]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.