Python Program to Calculate HCF (GCD) & LCM

This python program calculates Highest Common Factor (HCF) & Lowest Common Multiple (LCM) of two numbers given by user. HCF is also known as Greatest Common Divisor (GCD).

Highest Common Factor (HCF): The greatest common factor to any two or more than two integer numbers is known as HCF of these numbers. For example, HCF of 12 and 18 is 6. Also try: Calculate HCF Online

Lowest Common Multiple (LCM): The smallest or lowest common multiple of any two or more than two integer numbers is termed as LCM. For example, LCM of 12 and 18 is 36. Also try: Calculate LCM online

Python Source Code: HCF & LCM


# Python program to find hcf (gcd) & lcm

# Defining function to calculate hcf
def find_gcd(a,b):
    gcd = 1
    for i in range(1,a+1):
        if a%i==0 and b%i==0:
           gcd = i
    return gcd

# Reading numbers from user
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))

# Function call & displaying output HCF (GCD)
print('HCF or GCD of %d and %d is %d' %(first, second, find_gcd(first, second)))

# Calculating LCM
lcm = first * second / find_gcd(first, second)
print('LCM of %d and %d is %d' %(first, second, lcm))

HCF & LCM Python Program Output

Enter first number: 12
Enter second number: 18
HCF or GCD of 12 and 18 is 6
LCM of 12 and 18 is 36