如何高效地得到一系列数字的GCD和LCM?

发布于 2024-12-26 10:03:25 字数 254 浏览 5 评论 0原文

我目前使用此代码来查找 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

九歌凝 2025-01-02 10:03:25
from fractions import gcd
def lcm(a, b):
    return (a * b) // gcd(a, b)
from fractions import gcd
def lcm(a, b):
    return (a * b) // gcd(a, b)
欲拥i 2025-01-02 10:03:25

正如 Chris J 这个 SO问题所提到的提供算法。这是答案的 python 版本,它使用 reduce< /a> 内置和 fractions 模块自版本以来一直存在2.6。

import fractions

def gcd(*values):
    return reduce(fractions.gcd, values)

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 the fractions module that has been around since version 2.6.

import fractions

def gcd(*values):
    return reduce(fractions.gcd, values)
泅人 2025-01-02 10:03:25

您可以使用递归技术:

def gcd(a, b):
   if b == 0:
      return a
   else:
      return gcd(b, a%b)

将所有 GCD 值存储在哈希映射中。因此,当它执行递归步骤时,它首先访问哈希图以查看较小数字的 GCD 是否已经计算出来,如果您对大范围的输入执行此操作,这将节省大量时间。

You could use a recursive technique:

def gcd(a, b):
   if b == 0:
      return a
   else:
      return gcd(b, a%b)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文