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:
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.
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
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
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.
import math
a = 12
b = 15
gcd = math.gcd(a, b)
lcm = (a * b) // gcd
print("LCM of", a, "and", b, "is:", lcm)
Output
LCM of 12 and 15 is: 60
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.
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
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