Python代码 在线执行

Python 程序:查找 LCM

/examples/lcm

在此程序中,您将学习找到两个数字的 LCM 并显示它。

要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:


两个数字的最小公倍数(LCM)是可以被两个给定数字完全整除的最小正整数。

例如 12 和 14 的 LCM 是 84。

计算 LCM 的程序

# Python Program to find the LCM of two input number

def compute_lcm(x, y):

   # 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

num1 = 54
num2 = 24

print("The LCM is", compute_lcm(num1, num2))

输出

The LCM is 216

注意:要测试该程序,请更改num1num2的值。

该程序分别在num1num2中存储两个数字。 这些数字将传递到compute_lcm()函数。 该函数返回两个数字的 LCM。

在函数中,我们首先确定两个数字中的较大者,因为 LCM 只能大于或等于最大数。 然后,我们使用无限while循环从该数字开始及以后。

在每次迭代中,我们检查两个数字是否完美地除以我们的数字。 如果是这样,我们将数字存储为 LCM。 并摆脱循环。 否则,数字将增加 1,然后循环继续。

上面的程序运行较慢。 我们可以利用两个数的乘积等于这两个数的最小公倍数和最大公除数的乘积来提高效率。

Number1 * Number2 = LCM * GCD. 

这是一个实现此目的的 Python 程序。

使用 GCD 计算 LCM 的程序

# Python program to find the LCM of two input number

# This function computes GCD 
def compute_gcd(x, y):

   while(y):
       x, y = y, x % y
   return x

# This function computes LCM
def compute_lcm(x, y):
   lcm = (x*y)//compute_gcd(x,y)
   return lcm

num1 = 54
num2 = 24 

print("The LCM is", compute_lcm(num1, num2)) 

该程序的输出与以前相同。 我们有两个函数compute_gcd()compute_lcm()。 我们需要 GCD. 的数字以计算其 LCM

因此,compute_lcm()调用函数compute_gcd()完成此操作。 GCD 使用欧几里得算法可以有效地计算出两个数之和。

单击此处以了解有关用 Python 计算 GCD 的方法的更多信息。