Write a Python function to find the LCM of two numbers.
Posted by BobHarris
Last Updated: August 14, 2024
Finding the Least Common Multiple (LCM) in Python
The Least Common Multiple (LCM) of two integers is the smallest positive integer that is divisible by both numbers. A common method to calculate the LCM is to use the relationship between the LCM and the Greatest Common Divisor (GCD). The formula to determine the LCM of two numbers \(a\) and \(b\) is given by: \[ \text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)} \] To implement this in Python, you can use the math module, which provides a built-in function to calculate the GCD. Below is a function that calculates the LCM of two numbers using this approach.
import math

def lcm(a, b):
    """Calculate the Least Common Multiple (LCM) of two integers."""
    if a == 0 or b == 0:
        return 0  # LCM is not defined for 0
    return abs(a * b) // math.gcd(a, b)

# Example usage
num1 = 12
num2 = 18
result = lcm(num1, num2)
print(f"The LCM of {num1} and {num2} is: {result}")
Explanation of the Code
1. Importing the math module: This module contains the gcd function, which is essential for calculating the LCM. 2. Defining the LCM function: - The function lcm takes two parameters, a and b. - It first checks if either number is zero, as the LCM is not defined in this case, returning 0 instead. - The formula for LCM is applied: multiply the absolute values of a and b, and then divide by their GCD. 3. Example usage: The example demonstrates the function with two integers, 12 and 18. It outputs their LCM. This implementation efficiently computes the least common multiple and can be used for any pair of integers.
Related Content