我在使用这个算法时遇到了一些问题。我试图找到给定数字范围的最小公倍数。下面的函数求一个数的因数,数出数中不同的因数,数出因数,这样我就可以根据这个算法求出数范围的lcm,最后计算出lcm;但是,如果您运行此代码,则底部的打印语句不会打印正确的答案。相反,我得到一个我知道肯定不正确的数字。我主要需要第二双眼睛来指出这段代码的问题。任何人都可以帮忙吗?
from collections import defaultdict
def factors_of(number):
factors = [];
i = 2
while number >= 2:
if number % i == 0:
factors.append(i)
number = number / i
else:
i += 1
return factors
def count_factors(number):
count = {}
factors = factors_of(number)
for factor in factors:
if not factor in count:
count[factor] = 1
else:
count[factor] += 1
return count
def count_factors_of_numbers_in_range(start, stop):
count = defaultdict(int)
for number in range(start, stop):
factor_count = count_factors(number)
for key in factor_count:
if count[key] < factor_count[key]:
count[key] = factor_count[key]
return dict(count)
def find_lcm_of_numbers_in_range(start, stop):
count = count_factors_of_numbers_in_range(start, stop)
lcm = 1
for key in count:
total = count[key] * key
lcm = total * lcm
return lcm
print find_lcm_of_numbers_in_range(1, 21)