Program to Find the Least Common Multiple (LCM) in Python

Least Common Multiple (LCM)

The Least Common Multiple (LCM) of two numbers is the smallest positive integer that is divisible by both numbers. For example, the LCM of 12 and 18 is 36.

We will explore three different methods to find the LCM of two numbers using Python programming.

Method 1: Using HCF

The LCM of two numbers can be calculated using the formula:

LCM(a, b) = (a * b) / HCF(a, b)

def find_hcf(a, b):
    while b:
        a, b = b, a % b
    return a

def find_lcm(a, b):
    return (a * b) // find_hcf(a, b)

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"LCM of {num1} and {num2} is {find_lcm(num1, num2)}")
            

Output:

Enter first number: 12
Enter second number: 18
LCM of 12 and 18 is 36

Method 2: Using Iteration

We start from the maximum of the two numbers and keep increasing until we find a number that is divisible by both.

def find_lcm_iterative(a, b):
    max_num = max(a, b)
    while True:
        if max_num % a == 0 and max_num % b == 0:
            return max_num
        max_num += 1

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"LCM of {num1} and {num2} is {find_lcm_iterative(num1, num2)}")
            

Output:

Enter first number: 12
Enter second number: 18
LCM of 12 and 18 is 36

Method 3: Using Recursion

We use recursion to find the LCM by incrementing multiples of the larger number until we find a common multiple.

def find_lcm_recursive(a, b, multiple):
    if multiple % a == 0 and multiple % b == 0:
        return multiple
    return find_lcm_recursive(a, b, multiple + 1)

def find_lcm(a, b):
    return find_lcm_recursive(a, b, max(a, b))

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"LCM of {num1} and {num2} is {find_lcm(num1, num2)}")
            

Output:

Enter first number: 12
Enter second number: 18
LCM of 12 and 18 is 36
Numbers

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

HCF - Highest Common Factor: C C++ Java Python

LCM - Lowest Common Multiple: C C++ Java Python

GCD - Greatest Common Divisor: C C++ Java Python

Binary to Decimal Conversion: C C++ Java Python

Octal to Decimal Conversion: C C++ Java Python

Hexadecimal to Decimal Conversion: C C++ Java Python

Decimal to Binary Conversion: C C++ Java Python

Decimal to Octal Conversion: C C++ Java Python

Decimal to Hexadecimal Conversion: C C++ Java Python

Binary to Octal Conversion: C C++ Java Python

Quadrants in which a given coordinate lies: C C++ Java Python

Addition of Two Fractions: C C++ Java Python

Calculate the Area of a Circle: C C++ Java Python

Convert Digit/Number to Words: C C++ Java Python

Finding Roots of a Quadratic Equation: C C++ Java Python