Python Program to Find GCD of Two Numbers
def gcd(a, b): while b != 0: a, b = b, a % b return a.Examples
How to Think About It
Algorithm
Code
def gcd(a, b): while b != 0: a, b = b, a % b return a print(gcd(48, 18))
Dry Run
Let's trace gcd(48, 18) through the code
Initial values
a = 48, b = 18
First iteration
a, b = 18, 48 % 18 = 18, 12
Second iteration
a, b = 12, 18 % 12 = 12, 6
Third iteration
a, b = 6, 12 % 6 = 6, 0
End loop
b is 0, return a = 6
| a | b |
|---|---|
| 48 | 18 |
| 18 | 12 |
| 12 | 6 |
| 6 | 0 |
Why This Works
Step 1: Use the Euclidean algorithm
The Euclidean algorithm finds gcd by repeatedly replacing the larger number with the remainder of dividing it by the smaller number.
Step 2: Loop until remainder is zero
We keep updating the two numbers until the second number becomes zero, which means the first number is the gcd.
Step 3: Return the gcd
When the loop ends, the first number holds the greatest common divisor of the original two numbers.
Alternative Approaches
import math print(math.gcd(48, 18))
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) print(gcd(48, 18))
Complexity: O(log(min(a, b))) time, O(1) space
Time Complexity
The Euclidean algorithm runs in logarithmic time relative to the smaller input number because each step reduces the problem size significantly.
Space Complexity
The iterative approach uses constant extra space, only storing a few variables.
Which Approach is Fastest?
Using Python's built-in math.gcd is fastest and most optimized, while recursive and iterative implementations have similar time complexity but differ in readability and stack usage.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative Euclidean | O(log(min(a,b))) | O(1) | General use, efficient |
| Recursive Euclidean | O(log(min(a,b))) | O(log(min(a,b))) | Elegant code, small inputs |
| math.gcd built-in | O(log(min(a,b))) | O(1) | Fastest, simplest, recommended |