Python Program to Find HCF or GCD


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

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

# 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))


Enter first number: 50
Enter second number: 10
The H.C.F. of 50 and 10 is 10


Here, two integers stored in variables num1 and num2 are passed 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.