3个或更多数字的最小公倍数

编程入门 行业动态 更新时间:2024-10-09 09:12:39
本文介绍了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个或更多数字的最小公倍数

本文发布于:2023-11-29 10:02:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646084.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最小公倍数   数字   更多

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!