Python中的HCF和LCM - 使用Python计算HCF和LCM

462 阅读2分钟

嗨,编码员朋友们今天在本教程中,我们将学习如何使用python编程语言计算最高公因数(HCF)和最低公倍数(LCM)。

首先让我们了解一下两个数字的HCF和LCM是什么意思,如果你现在还不熟悉这些术语。


什么是最高公因数(HCF)?

两个数字的最高公因数被定义为这两个数字的最大公因数。例如,让我们考虑两个数字12和18。

这两个数字的公因数是2,3,和6。这三个数字中最高的是6,所以在这种情况下,HCF是6。


什么是最小公倍数(LCM)?

两个数字的最小/最低公倍数被称为两个数字的最低公倍数。例如,让我们再次考虑两个数字12和18。

这两个数字的乘数可以是36、72、108,等等。但是我们需要最小的公倍数,所以12和18的LCM将是36。


在Python中计算HCF和LCM

让我们直接进入在Python代码中实现HCF和LCM。

1.寻找两个数字的HCF

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

HCF = 1

for i in range(2,a+1):
    if(a%i==0 and b%i==0):
        HCF = i

print("First Number is: ",a)
print("Second Number is: ",b)
print("HCF of the numbers is: ",HCF)

让我们把两个数字作为输入,看看我们的结果是什么。

First Number is:  12
Second Number is:  18
HCF of the numbers is:  6

2.寻找两个数字的LCM

在我们计算了两个数字的HCF之后,找到LCM并不是一件难事。LCM仅仅等于数字的乘积除以数字的HCF。

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

HCF = 1

for i in range(2,a+1):
    if(a%i==0 and b%i==0):
        HCF = i

print("First Number is: ",a)
print("Second Number is: ",b)

LCM = int((a*b)/(HCF))
print("LCM of the two numbers is: ",LCM)

让我们通过这两个数字,看看结果是什么。

First Number is:  12
Second Number is:  18
LCM of the two numbers is:  36


总结

我希望你现在已经清楚了两个数字的HCF和LCM的计算方法。我想你也已经了解了在python编程语言中的实现方法。

谢谢你的阅读!学习愉快!😇