Python Program to Find HCF or GCD

112
views
Find HCF

In this program, you’ll learn how to find HCF or Greatest Common Divisor (GCD) using two different methods: function and loops and, Euclidean algorithm.

To properly understand this example to find HCF, you should have the knowledge of following Python programming topics:

  1. Python Recursion
  2. Python Functions
  3. Python Function Arguments

The greatest common divisor (G.C.D) or highest common factor (H.C.F) of two numbers is the largest positive integer that perfectly divides the two given numbers. For example, the H.C.F of 12 and 14 is 2.

Program to find the H.C.F of two input number

# Python program to find the H.C.F of two input number

# define a function
def computeHCF(x, y):

# choose the smaller number
    if x > y:
        smaller = y
    else:
        smaller = x
    for i in range(1, smaller+1):
        if((x % i == 0) and (y % i == 0)):
            hcf = i
            
    return hcf

num1 = 54 
num2 = 24

# take input from the user
# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))

print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

Output:

The H.C.F. of 54 and 24 is 6

In the above program, two integers stored in variables num1 and num2 and are passed to a function which returns the H.C.F.

First,  we determined the smaller no of the two since the HCF can only be less than or equal to the smallest number. And then we used a for loop to go from 1 to That number.

In each iteration, we first check if our number perfectly divides both the input numbers. If so, we store the number as H.C.F. At the completion of the loop, we end up with the largest number that perfectly divides both the numbers.

The method mentioned above is easy to understand and implement but it is not an efficient. A much more efficient method to find the H.C.F. is the Euclidean algorithm.

Euclidean algorithm

In this algorithm, we divide the greater by smaller and take the remainder. Now, divide the smaller by this remainder. Repeat until the remainder is 0.

For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24. The remainder is 6. Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required H.C.F.

Program to find H.C.F. of two numbers.

def computeHCF(x, y):

   # This function implements the Euclidian algorithm to find H.C.F. of two numbers
   while(y):
       x, y = y, x % y

   return x

computeHCF(300, 400)

Here we loop until y becomes zero. The statement x, y = y, x % y does swapping of values in Python. Click here to learn more about swapping variables in Python.

In each iteration, we place the value of y in x and the remainder (x % y) in y, simultaneously. When y becomes zero, we have H.C.F. in x.

Ask your questions and clarify your/others doubts on How to find HCF by commenting. Python Documentation