我想实现一个函数,它接受三个参数(x,low,high)作为输入 - 所有整数,并查找x
和{{之间low
因子的整数数1}}。例如,50到100之间有多少个整数有4个因子?
我的代码如下:
high
当我尝试运行此操作时,我得到的结果不正确,例如
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
这应列出10到20之间的四个素数 功能有效,但没有。任何帮助非常感谢!
答案 0 :(得分:0)
您需要在每次迭代结束时将div_count
设置为零:
def n_factors(x, lower, upper):
int_counter = 0 # integer counter
div_count = 0 # divisor counter
for i in range(lower, upper+1):
for j in range(1, i + 1):
if (i%j)==0:
div_count += 1
if div_count == x:
print i
int_counter += 1
div_count = 0
return int_counter
答案 1 :(得分:0)
def n_factors(x, lower, upper):
facs = {}
for f in range(1, int(upper**0.5)+1):
for n in range(lower+f-(lower%f), upper+1, f):
if n not in facs: facs[n] = []
facs[n].append(f)
for n, numFacs in facs.items():
if len(numFacs) != x: continue
print(n)
答案 2 :(得分:0)
def n_factors(x, lower, upper):
""" Find how many integers have x (user-specified)
factors from - lower to upper - (user-specified) """
int_counter = 0
div_count = 0
for i in range(lower, upper+1):
for j in range(1, i+1):
if (i%j)==0:
div_count += 1
if (div_count == x):
print i
int_counter += 1
div_count = 0
return int_counter
答案 3 :(得分:0)
您可以通过略高的编码轻松避免这样的错误。
如果您需要计算这种情况发生的次数",您不需要设置手动计数器而忘记重置它 - 您可以将该句子直接翻译成蟒蛇;这里的条件是" j
除i
而没有余数":
for i in range(lower, upper+1):
div_count = sum(i%j == 0 for j in range(1,i+1))