Python Program to Find HCF or GCD

In this example, we will write a program that finds the Highest Common Factor or Greatest Common Divisor of two or more integers. To better understand this example, make sure you have knowledge of the following tutorials:-

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.

Python Program to Find HCF or GCD

def calculate_hcf(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 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

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

The output of the above program is:-

Enter first number: 20
Enter second number: 35
The H.C.F. of 20 and 35 is 5
Program Explanation:-
The input() function takes two numbers from user.  A function named calculate_hcf is created to calculate the HCF which takes two arguments x and y. The smallest number is found out and is used to get the smallest divisible value using for loop. If the number divides both x and y numbers, then that is stored in hcf value and is returned as the loop is over. The final result is printed on the user screen.
SHARE Python Program to Find HCF or GCD

You may also like...

Leave a Reply

Your email address will not be published.

Share