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
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).

After this program

If the idea is still fuzzy, read Day 9: Loops and Iteration in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 loop programs, or see every topic on Python exercises.