我目前正在使用一个函数,该函数接受两个数字并使用循环查找这些数字的最小公倍数,

def lcm(x, y):
   """This function takes two
   integers and returns the L.C.M."""

   # Choose the greater number
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm
Python中是否有内置模块可以代替编写自定义函数呢?

最佳答案

在Python 3.8和更早版本中
stdlib中没有内置这样的东西。
但是,math库中有一个Greatest Common Divisor函数。 (对于Python 3.4或2.7,将其埋在fractions中。)在GCD之上编写LCM非常简单:

def lcm(a, b):
    return abs(a*b) // math.gcd(a, b)
或者,如果您使用的是NumPy,它现在已经有相当一段时间提供了 lcm 函数。

关于python - 内置模块计算最小公倍数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51716916/

10-12 18:11