Solution Review: Find the Greatest Common Divisor
This review provides a detailed analysis of the solution to find the greatest common divisor.
We'll cover the following
Solution: Using Recursion
def gcd(testVariable1, testVariable2) :# Base Caseif testVariable1 == testVariable2 :return testVariable1# Recursive Caseif testVariable1 > testVariable2 :return gcd(testVariable1 - testVariable2, testVariable2)else :return gcd(testVariable1, testVariable2 - testVariable1)# Driver Codenumber1 = 6number2 = 9print(gcd(number1, number2))
Explanation
The naive approach to finding of numbers is to list all their divisors. Then pick the common divisors, and then select the greatest out of them.
However, a simple mathematical simplification can make our task easier.
The idea behind calculating is: If , is the same as .
This is because if and both leave no remainder, then leaves no remainder.
This leads to the following algorithm:
Let’s have a look at the code execution:
In the next lesson, we have another challenge for you to solve.