3个或更多数字的最小公倍数 [英] Least common multiple for 3 or more numbers

查看:35
本文介绍了3个或更多数字的最小公倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算多个数的最小公倍数?

到目前为止,我只能在两个数字之间进行计算.但不知道如何扩展它以计算 3 个或更多数字.

到目前为止,我就是这样做的

LCM = num1 * num2/gcd ( num1 , num2 )

with gcd 是计算数字的最大公约数的函数.使用欧几里得算法

但我不知道如何计算 3 个或更多数字.

解决方案

In Python(已修改 primes.py):

def gcd(a, b):"""使用欧几里德算法返回最大公约数."""而 b:a, b = b, a % b返回一个def lcm(a, b):"""返回最小公倍数."""返回 a * b//gcd(a, b)def lcmm(*args):"""返回参数的 lcm."""返回减少(lcm,args)

用法:

<预><代码>>>>液晶(100, 23, 98)112700>>>lcmm(*范围(1, 20))232792560

reduce() 的作用类似于那个:

<预><代码>>>>f = lambda a,b: "f(%s,%s)" % (a,b)>>>打印减少(f,abcd")f(f(f(a,b),c),d)

How do you calculate the least common multiple of multiple numbers?

So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.

So far this is how I did it

LCM = num1 * num2 /  gcd ( num1 , num2 )

With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm

But I can't figure out how to calculate it for 3 or more numbers.

解决方案

In Python (modified primes.py):

def gcd(a, b):
    """Return greatest common divisor using Euclid's Algorithm."""
    while b:      
        a, b = b, a % b
    return a

def lcm(a, b):
    """Return lowest common multiple."""
    return a * b // gcd(a, b)

def lcmm(*args):
    """Return lcm of args."""   
    return reduce(lcm, args)

Usage:

>>> lcmm(100, 23, 98)
112700
>>> lcmm(*range(1, 20))
232792560

reduce() works something like that:

>>> f = lambda a,b: "f(%s,%s)" % (a,b)
>>> print reduce(f, "abcd")
f(f(f(a,b),c),d)

这篇关于3个或更多数字的最小公倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆