Implementing HCF and LCM in Python. When we dive into the world of numbers and their relationships, to fundamental concepts that are the Highest Common Factor (HCF) and Least Common Multiple (LCM). In this article, we will explore how to compute the LCM and HCF of numbers using Python.

## Table of Contents

## Computing HCF in Python

To calculate the HCF of two numbers in Python, We can utilize Euclidean, a time-tested method that relies on the principle that the GCD of two numbers also divides their difference.

```
def compute_HCF(x,y):
while(y):
x,y = y,x%y
return x
```

In this function,` 'x'`

represents one of the numbers and `'y'`

represents the other. The `while`

loop continues until `'y'`

becomes 0. At each iteration, `'x'`

takes the value of `'y'`

, and `'y'`

takes the value of the remainder when `'x'`

divided by `'y'`

. When `'y'`

becomes 0, `'x'`

contains the HCF of the two numbers.

## Computing LCM in Python

The LCM of two numbers can be easily found if we know their HCF, Using the formula-

**LCM(x,y) = (x*y)/HCF(x,y) **

```
def compute_LCM(x,y):
lcm = (x*y)//compute_HCF(x,y)
return lcm
```

We can leverage the previously defined `'compute_HCF'`

function to create an LCM computing function.

## Python Program for Calculating LCM and HCF

```
def compute_HCF(x,y):
while(y):
x,y = y,x%y
return x
def compute_LCM(x,y):
lcm = (x*y)//compute_HCF(x,y)
return lcm
num1 = 5
num2 = 10
print("HCF of ",num1,"and ",num2,"is ", compute_HCF(num1,num2))
print("LCM of ",num1,"and ",num2,"is ", compute_LCM(num1,num2))
```

*Happy Coding & Learning*

## 4 thoughts on “Implementing HCF and LCM in Python”