Javatpoint Logo
Javatpoint Logo

Python Program to Find HCF

In the following tutorial, we will understand how to find Highest Common Factor (HCF) in the Python programming language.

But before we get started, let us briefly discuss about HCF.

HCF: Highest Common Factor

Highest Common Factor or Greatest Common Divisor of two or more integers when at least one of them is not zero is the largest positive integer that evenly divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4.

For example:

We have two integers 8 and 12. Let's find the HCF.

The divisors of 8 are:

The divisors of 12 are:

HCF /GCD is the greatest common divisor. So HCF of 8 and 12 are 4.

Now, let us consider an example based on finding HCF of two given numbers.

Example:

Output:

Enter first number: 8
Enter second number: 12
The H.C.F. of 8 and 12 is 4

Explanation:

In the above snippet of code, two integers stored in variable num1 and num2 are passed to the calculate_hcf() function. The function calculates the HCF these two numbers and returns it.

Within the function, we have to determine the smaller number as the HCF can only be less than or equal to the smallest number. We have then used a for loop in order go from 1 to that number.

In every iteration, we have to check if the number perfectly divides both the input numbers. If it does, we have to stored the number as HCF. At the loop completion, we end up with the largest number that perfect divides both the numbers.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA