找到数字1-20的最小公倍数

时间:2013-07-18 05:54:56

标签: python

我在使用此算法时遇到了一些麻烦。我试图找到给定范围的数字的最小公倍数。以下函数查找数字的因子,计算数字中的不同因子,计算因子,以便我可以根据this算法找到数字范围的lcm,然后最终计算lcm;但是,如果运行此代码,则底部的print语句不会打印正确的答案。相反,我得到一个我知道肯定是不对的号码。我主要需要第二组眼睛来指出这段代码的问题。有人可以帮忙吗?

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)

2 个答案:

答案 0 :(得分:0)

为什么你不能简单地通过euclid的算法找到gcd并乘以数字并除以gcd来找到LCM?

def decorator(d):
    """This is a decorator that will decorate all decorators. This will add update_wrapper
    to all decorators.
    (fun) -> fun
    """
    def _d(f):
        return update_wrapper(d(f), f)
    return update_wrapper(_d, d)



@decorator
def nary(f):
    """This is docp implementation of n_ary function above.
    (function) -> function
   Tue-23-April-2013
    """
    def n_ary(x, *args):
        if len(args) == 0:
            return x
        return f(x, n_ary(*args))
    return n_ary

@nary
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

答案 1 :(得分:0)

我弄清楚我做错了什么。我想我只需要睡个好觉。

问题不在于Python的怪癖(这是我认为的可能),而是在我自己的算法实现中。在我的代码中

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

我搞砸了在total语句中将所有数字相乘。我不需要将数字2乘以数字4,而是需要将2乘以4(2 ** 4)。只需将代码调整为

即可
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 = key ** count[key]
        lcm = total * lcm
    return lcm
一切顺利,我现在很高兴。 :)