Python Program to Find HCF or GCD


To understand this example, you should have knowledge of following Python programming topics:
The highest common factor (H.C.F) or greatest common divisor (G.C.D) 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.

Source Code


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

# define a function
def hcf(x, y):
   """This function takes two
   integers and returns the H.C.F"""

   # 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


# 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", hcf(num1, num2))
Output

Enter first number: 54
Enter second number: 24
The H.C.F. of 54 and 24 is 6
This program asks for two integers and passes them to a function which returns the H.C.F. In the function, we first determine the smaller of the two number since the H.C.F can only be less than or equal to the smallest number. We then use a for loop to go from 1 to that number. In each iteration we 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 above method is easy to understand and implement but not efficient. A much more efficient method to find the H.C.F. is the Euclidean algorithm.

Euclidean algorithm

This algorithm is based on the fact that H.C.F. of two numbers divides their difference as well. 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. We can do this in Python as follows.

Source Code


def hcf(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
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.

Comments