Python Program to Find the GCD and LCM of Two Numbers
Beginner · Numbers · CBSE class 11 practical list
The GCD (greatest common divisor, also called the HCF) of two numbers is the largest number that divides both of them exactly. The LCM (least common multiple) is the smallest number that both of them divide into. This program finds the GCD with Euclid's method and then uses it to get the LCM.
Program
GCD (HCF) of 36 and 60 is 12 LCM of 36 and 60 is 180
How it works
- Euclid's method keeps replacing
xwithy, andywith the remainderx % y. - The remainders get smaller each time, and when one becomes 0, the value left in
xis the GCD. - For two positive numbers, GCD x LCM = a x b, so the LCM is
(a * b) // gcd. //is whole-number division, so the LCM comes out as an integer rather than a decimal.
Other ways to write it
Using the math module
GCD of 36 and 60 is 12 LCM of 36 and 60 is 180
math.gcd() and math.lcm() do the same work in one call each; math.lcm() needs Python 3.9 or newer.
By checking every divisor
GCD: 12 LCM: 180
This slower textbook approach tries every number up to the smaller one and keeps the last one that divides both.
Try it yourself
Change the numbers to 17 and 5 and see why their GCD is 1.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises