嘿,编码员朋友!今天在本教程中,我们将学习如何使用 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
1
2
3
4
5
6
7
8
9
10
11
12
|
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. 求两个数的最小公倍数
当我们计算出两个数字的 HCF 后,找到 LCM 并不是一件困难的任务。LCM 简单地等于数字除以数字的 HCF 的乘积。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 编程语言中相同内容的实现。
感谢您的阅读!快乐学习!😇