编写一个 Python 程序,使用 While 循环、函数和递归查找两个数字的最小公倍数(LCM)。
在数学中,两个或多个整数的最小公倍数(LCM)是能够被给定整数值整除而没有余数的最小正整数。例如,整数 2 和 3 的 LCM 值是 12,因为 12 是能被 2 和 3 整除的最小正整数(余数为 0)。
Python 程序使用 while 循环查找两个数字的 LCM
此 Python 程序允许用户输入两个正整数值。在 Python while 循环中,我们使用 If 语句来检查 maximum % a 和 maximum % b 的余数是否等于零。如果为真,则最小公倍数 = maximum;否则,跳过该值。
# using If Else and While loop
a = float(input(" Please Enter the First Value a: "))
b = float(input(" Please Enter the Second Value b: "))
if(a > b):
maximum = a
else:
maximum = b
while(True):
if(maximum % a == 0 and maximum % b == 0):
print("\n Least Common Multiple of {0} and {1} = {2}".format(a, b, maximum))
break;
maximum = maximum + 1

使用函数计算两个数字的 LCM
此 Python 程序与上面相同。但是,我们将逻辑使用 函数进行了分离。
def findLeastCM(a, b):
if(a > b):
maximum = a
else:
maximum = b
while(True):
if(maximum % a == 0 and maximum % b == 0):
Val = maximum;
break;
maximum = maximum + 1
return Val
num1 = float(input(" Please Enter the First : "))
num2 = float(input(" Please Enter the Second : "))
Val = findLeastCM(num1, num2)
print("\n Least Common Multiple of {0} and {1} = {2}".format(num1, num2, Val))
Please Enter the First : 20
Please Enter the Second : 45
Least Common Multiple of 20.0 and 45.0 = 180.0
编写上述程序的更好方法是使用函数查找两个数字的 LCM。
def LeastCommonFactor(a, b):
maximum = max(a,b)
result = maximum
while True:
if result % a == 0 and result % b == 0:
return result
result += maximum
a = int(input("Enter the First = "))
b = int(input("Enter the Second = "))
print("Least Common Multiple = ", LeastCommonFactor(a, b))

使用 GCD 计算两个数字的 LCM
此 程序查找两个数字的 GCD。在这里,我们使用 Temp 变量来查找它。使用此,我们计算 LCM。
num1 = float(input(" Please Enter the First : "))
num2 = float(input(" Please Enter the Second : "))
a = num1
b = num2
while(num2 != 0):
temp = num2
num2 = num1 % num2
num1 = temp
hcf = num1
print("\n HCF of {0} and {1} = {2}".format(a, b, hcf))
Val = (a * b) / hcf
print("\n Result of {0} and {1} = {2}".format(a, b, Val))

Python 程序使用递归查找两个数字的 LCM
此程序允许用户输入两个正整数值,并通过递归调用 fdhcf 函数来计算这两个值的 LCM。
def fdhcf(a, b):
if(b == 0):
return a;
else:
return fdhcf(b, a % b)
num1 = float(input(" Please Enter the First Value : "))
num2 = float(input(" Please Enter the Second Value : "))
gcd = fdhcf(num1, num2)
print("\n GCD of {0} and {1} = {2}".format(num1, num2, gcd))
res = (num1 * num2) / gcd
print("\n LCM of {0} and {1} = {2}".format(num1, num2, res))
