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
- Read the two numbers.
- Find the GCD with Euclid's method: replace (x, y) with (y, x % y) until y is 0.
- 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
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
- Compare the answer with
math.gcd(a, b). - Find the GCD of three numbers by applying the method twice.
Common mistakes
- Changing
aandbdirectly and then having nothing left to calculate the LCM with. - Using
/for the LCM, which gives a decimal result.