find the least common multiple of two numbers in python

One way to find the least common multiple (LCM) of two numbers in python is by using the built-in math module's gcd() function to find the greatest common divisor (GCD) of the two numbers, and then using the formula LCM = (a*b)//gcd(a,b) to calculate the LCM. Here's the code:

main.py
import math

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

# Example usage
print(lcm(12, 18))  # Output: 36
111 chars
8 lines

In the code above, we define a function lcm() that takes two numbers a and b as input, and returns their LCM using the formula LCM = (a*b) // gcd(a,b). We use the // operator to ensure integer division, since the LCM must be an integer. Finally, we use the print() function to demonstrate usage of the lcm() function with two example inputs, 12 and 18. The output should be 36, which is the least common multiple of 12 and 18.

gistlibby LogSnag