HCF and LCM in Python – Calculating the HCF and LCM using Python

Feature Img Hcf Lcm

Hey fellow coder! Today in this tutorial, we will learn how to compute the highest common factor (HCF) and Lowest common multiplier (LCM) using the python programming language.

Let us first understand what do we mean by HCF and LCM of two numbers if you are not familiar with these terms as of now.

Also read: Calculating Precision in Python — Classification Error Metric


What is Highest Common Factor (HCF)?

The highest common factor of two numbers is defined as the greatest common factor of the two numbers. For example, let’s consider two numbers 12 and 18.

The two numbers mentioned have the common factors as 2,3, and 6. The highest out of the three is 6. So in this case the HCF is 6.


What is Lowest Common Multiplier (LCM)?

The smallest/lowest common multiple of the two numbers is called the lowest common multiplier of the two numbers. For example, let’s consider the two numbers 12 and 18 again.

The multipliers of the two numbers can be 36, 72, 108, and so on. But we need the lowest common multipliers so the LCM of 12 and 18 will be 36.


Calculate HCF and LCM in Python

Let’s get right into implementing HCF and LCM in Python code.

1. Finding HCF of two numbers

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)

Let us pass two numbers as input and see what our results come out to be.

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

2. Finding LCM of two numbers

After we have computed the HCF of the two numbers, finding the LCM is not a tough task. LCM is simply equal to the product of the number divided by the HCF of the numbers.

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)

Let us pass the two numbers and see what the results turn out to be.

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

Conclusion

I hope you are now clear with the computation of HCF and LCM of two numbers. And I guess you have also learned about the implementation of the same in the python programming language.

Thank you for reading! Happy learning! 😇