![]() |
VOOZH | about |
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
Below are some of the ways by which we can find the LCM of two numbers in Python:
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.
LCM of 12 and 15 is 60
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.
LCM of 12 and 15 is: 60
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.
LCM of 12 and 15 is: 60