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 browser
1# Program to find LCM of two numbers using GCD
2
3a = int(input("Enter first integer: "))
4b = int(input("Enter second integer: "))
5
6orig_a, orig_b = a, b
7
8while b != 0:
9 a, b = b, a % b
10
11gcd = abs(a)
12lcm = abs(orig_a * orig_b) // gcd if gcd != 0 else 0
13
14print("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).