Open In App

Python Program to Find LCM of Two Numbers

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given two numbers and our task is to find the LCM of two numbers in Python. In this article, we’ll discuss different approaches to finding the LCM of two numbers in Python.

Example:

Input: a = 12, b = 15
Output: 60
Explanation: LCM of 12 and 15 is 60

Python Program to Find LCM of Two Numbers

Below are some of the ways by which we can find the LCM of two numbers in Python:

Find the LCM of Two Numbers Using Loop

In this example, the function LCM(a, b) calculates the Least Common Multiple (LCM) of two numbers a and b by iterating through multiples of the greater number within a range up to their product, and returns the first multiple that is divisible by the smaller number.

Python3
def LCM(a, b):
    greater = max(a, b)
    smallest = min(a, b)
    for i in range(greater, a*b+1, greater):
        if i % smallest == 0:
            return i

# Driver program to test above function
if __name__ == '__main__':
    a = 12
    b = 15
    print("LCM of", a, "and", b, "is", LCM(a, b))

Output
LCM of 12 and 15 is 60

Find LCM of Two Numbers Using the GCD (Greatest Common Divisor)

In this example, the function lcm_using_gcd(a, b) utilizes the property that the LCM of two numbers a and b is equal to their product divided by their greatest common divisor (GCD), calculated using math.gcd(). It then returns the computed LCM.

Python3
import math

def lcm_using_gcd(a, b):
    gcd = math.gcd(a, b)
    lcm = (a * b) // gcd
    return lcm

# Example usage:
num1 = 12
num2 = 15
print("LCM of", num1, "and", num2, "is:", lcm_using_gcd(num1, num2))

Output
LCM of 12 and 15 is: 60

Find LCM of Two Numbers Using Prime Factorization

In this example, the prime_factors(n) function generates the prime factors of a given number n, while lcm_using_prime_factors(a, b) computes the Least Common Multiple (LCM) of two numbers a and b using their prime factorizations. It combines the prime factors of both numbers, taking the maximum occurrences of each prime factor, and calculates their product to determine the LCM.

Python3
def prime_factors(n):
    factors = []
    divisor = 2
    while n > 1:
        while n % divisor == 0:
            factors.append(divisor)
            n //= divisor
        divisor += 1
    return factors

def lcm_using_prime_factors(a, b):
    factors_a = prime_factors(a)
    factors_b = prime_factors(b)
    lcm = 1
    for factor in set(factors_a + factors_b):
        lcm *= factor ** max(factors_a.count(factor), factors_b.count(factor))
    return lcm

# Example usage:
num1 = 12
num2 = 15
print("LCM of", num1, "and", num2, "is:", lcm_using_prime_factors(num1, num2))

Output
LCM of 12 and 15 is: 60


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads