Python Program to Find HCF and LCM of Two Numbers

Highest Common Factor (HCF)

HCF is one of the most important concepts to understand. The HCF of two or more numbers is the largest number that divides evenly into all of the numbers.

For example:

The factors of 24 are 1, 2, 3, 4, 6, 8, 12, and 24.

The factors of 16 are 1, 2, 4, 8, and 16.

The common factors between the two numbers are 1, 2, 4, and 8.

The HCF of 24 and 16 is 8.

Lowest Common Multiplier (LCM)

The lowest common multiple (LCM) of two or more integers is the smallest positive integer which is a multiple of all of the integers.

The LCM of two numbers is the smallest positive integer that is a multiple of both numbers.

For example, the LCM of 10 and 15 is 30.

Program Code

def hcf(x, y):
    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

def lcm(x, y):
    if x > y:
        greater = x
        greater = y
        if((greater % x == 0) and (greater % y == 0)):
            lcm = greater
        greater += 1
    return lcm

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))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

Input Given:

Enter first number: 24
Enter second number: 16

Expected Output:

The H.C.F. of 24 and 16 is 8
The L.C.M. of 24 and 16 is 48

Code Explanation

  1. The hcf() function takes two numbers as parameters and returns the HCF of those numbers.
  2. The lcm() function takes two numbers as parameters and returns the LCM of those numbers.
  3. The user is asked to enter two numbers.
  4. The hcf() and lcm() functions are called with the two numbers as arguments.
  5. The HCF and LCM of the two numbers are displayed.

Leave a Comment

Share to...