Python Program to Find the GCD Using Recursion
Beginner · Recursion
The GCD (greatest common divisor), also called the HCF (highest common factor), of two numbers is the largest number that divides both of them exactly, so the GCD of 48 and 18 is 6. This program uses Euclid's algorithm, which says the GCD of a and b is the same as the GCD of b and a % b. That rule calls itself on smaller numbers, so it is naturally recursive.
Program
GCD of 48 and 18 is 6 LCM of 48 and 18 is 144
How it works
- Euclid's rule works because any number that divides both
aandbalso dividesa % b, the remainder whenais divided byb, sogcd(a, b)equalsgcd(b, a % b). - Each call works with smaller numbers:
gcd(48, 18)becomesgcd(18, 12), thengcd(12, 6), thengcd(6, 0). - The base case is
b == 0, because every number divides 0, so the GCD ofaand 0 isa, here 6. - The LCM (lowest common multiple) is then
a * b // result, because the product of two numbers equals their GCD times their LCM.
Other ways to write it
Showing each step
Step 1: gcd(252, 105) Step 2: gcd(105, 42) Step 3: gcd(42, 21) Step 4: gcd(21, 0) Answer: 21
Printing each call shows how quickly the numbers shrink: 252 and 105 need only four calls to reach the answer, 21.
Using subtraction
GCD of 48 and 18: 6 Check with math.gcd(): 6
Euclid's original method subtracts the smaller number from the larger until they are equal, which takes more calls than the % version and only works for positive numbers; math.gcd() is the built-in way.
Try it yourself
Find the GCD of three numbers, 36, 60 and 84, by calling gcd() twice.
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