如何高效地得到一系列数字的GCD和LCM?
我目前使用此代码来查找 gcd 和 lcm
def gcd(a, b):
while b != 0:
a, b = b, a%b
return a
def lcm(a, b):
result = a*b/gcd(a,b)
return result
但是,如果我想对数字列表(例如 [4,5,7,1,5,7,10,1,16,24] 等)执行此操作,该怎么办?我是否受限于循环?
I currently use this code to find gcd and lcm
def gcd(a, b):
while b != 0:
a, b = b, a%b
return a
def lcm(a, b):
result = a*b/gcd(a,b)
return result
But what if I want to do this for a list of numbers e.g. [4,5,7,1,5,7,10,1,16,24] etc? Am I constrained to loops?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Chris J 这个 SO问题所提到的提供算法。这是答案的 python 版本,它使用
reduce
< /a> 内置和fractions
模块自版本以来一直存在2.6。As mentioned by Chris J this SO question provides the algorithm. Here is a python version of the answer that uses the
reduce
built-in and thefractions
module that has been around since version 2.6.您可以使用递归技术:
将所有 GCD 值存储在哈希映射中。因此,当它执行递归步骤时,它首先访问哈希图以查看较小数字的 GCD 是否已经计算出来,如果您对大范围的输入执行此操作,这将节省大量时间。
You could use a recursive technique:
Store all your GCD values in a hash map. So, when it does the recursive step, it first accesses the hash map to see if the GCD of the smaller numbers has already been computed, which will save a lot of time if you were doing this for a large range of inputs.