In this tutorial, we will learn how to find the HCF (Highest Common Factor) of n numbers using Python. HCF, also called GCD (Greatest Common Divisor), is the highest number that can divide each given number.
Finding the HCF of a series of numbers is an essential operation in number theory and has applications in areas such as least common multiples and cryptography.
There are multiple methods to find the HCF of a set of numbers, and in this tutorial, we’ll focus on using math.gcd function and a custom recursive function to achieve this.
Step 1: Install Required Package
First, we will need the math package, which comes pre-installed with Python. However, if you don’t have it, you can install it by typing:
1 |
pip install mpmath |
Step 2: Import Required Libraries
Once the package is installed, we can import the required libraries in our Python script.
1 |
import math |
Step 3: FindThe HCF of Two Numbers
The math package has the ‘gcd’ function that calculates the HCF of two numbers. Let’s see how it works:
1 2 3 4 5 |
number1 = 20 number2 = 30 hcf = math.gcd(number1, number2) print("HCF of", number1, "and", number2, "is", hcf) |
Executing the above code will result in the following output:
HCF of 20 and 30 is 10
Step 4: Find the HCF of n Numbers
Let’s write a function to find the HCF of n numbers using math.gcd function:
1 2 3 4 5 |
def find_hcf(numbers): hcf = numbers[0] for num in numbers[1:]: hcf = math.gcd(hcf, num) return hcf |
We can now use this function to find the HCF of any given list of numbers:
1 2 3 |
numbers = [45, 60, 75] result = find_hcf(numbers) print("HCF of", numbers, "is", result) |
Executing the above code will result in the following output:
HCF of [45, 60, 75] is 15
Full code:
1 2 3 4 5 6 7 8 9 10 11 |
import math def find_hcf(numbers): hcf = numbers[0] for num in numbers[1:]: hcf = math.gcd(hcf, num) return hcf numbers = [45, 60, 75] result = find_hcf(numbers) print("HCF of", numbers, "is", result) |
Conclusion
In this tutorial, we have learned how to find the HCF (Highest Common Factor) of a set of numbers using Python.
The math package’s ‘gcd’ function makes it easy to find the HCF of two numbers, and we have used this to create a function that calculates the HCF of n numbers. This tutorial should have given you a good understanding of the HCF concept and how to implement it in Python.