What is the most efficient way to calculate the least common multiple of two integers?

后端 未结 14 1892

What is the most efficient way to calculate the least common multiple of two integers?

I just came up with this, but it definitely leaves something to be desired.

14条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 13:50

    Here is a highly efficient approach to find the LCM of two numbers in python.

    def gcd(a, b):
        if min(a, b) == 0:
            return max(a, b)
        a_1 = max(a, b) % min(a, b)
        return gcd(a_1, min(a, b))
    
    def lcm(a, b):
        return (a * b) // gcd(a, b)
    

提交回复
热议问题