Write Python. Understand every error.

Open the editor

Python programs · Numbers

Python program to find the GCD and LCM of two numbers

The greatest common divisor (GCD) is the largest number that divides both; the least common multiple (LCM) is the smallest number both divide into.

Approach

  1. Read the two numbers.
  2. Find the GCD with Euclid's method: replace (x, y) with (y, x % y) until y is 0.
  3. Get the LCM from the rule GCD × LCM = a × b.

The program

a, b = map(int, input().split())
x, y = a, b
while y != 0:
    x, y = y, x % y
gcd = x
lcm = a * b // gcd
print("GCD:", gcd)
print("LCM:", lcm)

Sample run

Input
12 18
Output
GCD: 6
LCM: 36

Run this program in Py-CRAFT

How the code works

The GCD does not change when (x, y) becomes (y, x % y), and the process ends when y reaches 0. For 12 and 18 the pairs are (12, 18), then (18, 12), then (12, 6), then (6, 0), so the GCD is 6. The LCM follows from 12 × 18 ÷ 6 = 36. The copy x, y = a, b keeps the original numbers for that last step.

Try changing it

Common mistakes

Learn the ideas

More programs

Share this page: