如何有效地获得一系列数字的GCD和LCM? [英] How to get GCD and LCM of a range of numbers efficiently?

查看:106
本文介绍了如何有效地获得一系列数字的GCD和LCM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用此代码查找gcd和lcm

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

但是如果我想对数字列表进行此操作,例如[4,5,7,1,5,7,10,1,16,24]等?我受制于循环吗?

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?

推荐答案

如Chris J所述 reduce 内置的答案的python版本以及 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 the fractions module that has been around since version 2.6.

import fractions

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

这篇关于如何有效地获得一系列数字的GCD和LCM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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