LCM of Two Numbers (Loop)

Compute the least common multiple (LCM) of two integers using GCD.

PythonBeginner
Python
# Program to find LCM of two numbers using GCD

a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))

orig_a, orig_b = a, b

while b != 0:
    a, b = b, a % b

gcd = abs(a)
lcm = abs(orig_a * orig_b) // gcd if gcd != 0 else 0

print("LCM is", lcm)

Output

Enter first integer: 12
Enter second integer: 18
LCM is 36

We first find GCD with the Euclidean algorithm, then use the identity LCM(a, b) = |a × b| / GCD(a, b).