【发布时间】:2015-10-14 14:28:57
【问题描述】:
我想实现一个函数,该函数将三个参数(x、low、high)作为输入 - 所有整数,并找到在 low 和 high 之间具有 x 因子的整数的数量。例如,50 到 100 之间有多少个整数有 4 个因数?
我的代码如下:
def n_factors(x, lower, upper):
""" Find how many integers have x (user-specified)
factors from - lower to upper - (user-specified) """
int_counter = 0 # integer counter
div_count = 0 # divisor counter
for i in range(lower, upper+1):
for j in range(2, i):
if (i%j)==0:
div_count += 1
if (div_count == x):
print i
int_counter += 1
return int_counter
当我尝试运行它时,我得到了不正确的结果,例如
n_factors(2,10,20)
10
11
2
这应该列出 10 到 20 之间的四个素数,如果 该功能有效,但没有。非常感谢任何帮助!
【问题讨论】:
-
输出中的 10 怎么样? 10有4个因数,即1,2,5,10。你的意思是
at least 2 factors? -
@inspectorG4dget:我不确定,这个函数没有做我想做的事情
-
n_factors(2,10,20)的期望输出是什么? -
@inspectorG4dget:我的意思是 2 个因子,即在这种情况下是素数。但我希望该函数对任意两个整数之间的任意数量的因子都是通用的
-
您希望因子为素数还是任意因子?例如,您是否期望 n_factors(4, 10, 20) 计数为 12,因为 {2, 3, 4, 6} 是它的因数(不包括 1 和它本身,12)?
标签: python function number-theory