LCM of Two Numbers (Loop) in Python
Compute the least common multiple (LCM) of two integers using GCD.
BeginnerLoop ProgramsExample 11 of 25
lcm-of-two-numbers-loop.py
Run in browser1# Program to find LCM of two numbers using GCD23a = int(input("Enter first integer: "))4b = int(input("Enter second integer: "))56orig_a, orig_b = a, b78while b != 0:9 a, b = b, a % b1011gcd = abs(a)12lcm = abs(orig_a * orig_b) // gcd if gcd != 0 else 01314print("LCM is", lcm)
Output
Enter first integer: 12 Enter second integer: 18 LCM is 36
What's going on
We first find GCD with the Euclidean algorithm, then use the identity LCM(a, b) = |a × b| / GCD(a, b).