Last Updated : 23 Jul, 2025
The task of finding the GCD (Greatest Common Divisor) of two numbers in Python involves determining the largest number that divides both input values without leaving a remainder. For example, if a = 60 and b = 48, the GCD is 12, as 12 is the largest number that divides both 60 and 48 evenly.
Using euclidean algorithmEuclidean algorithm repeatedly replaces the larger number with the remainder of the division until the remainder is zero. The last non-zero divisor is the GCD.
Python
a = 60 # first number
b = 48 # second number
# loop until the remainder is 0
while b != 0:
a, b = b, a % b
print(a)
Explanation: while loop runs until b becomes 0. In each iteration, a is updated to b and b is updated to a % b. When b becomes 0, the value of a is the GCD .
Using math.gcd()math.gcd() function is a built-in function in python hence an efficient way to find the GCD of two numbers in Python, internally using the Euclidean algorithm.
Python
import math
a = 60 # first number
b = 48 # second number
print(math.gcd(a, b))
Explanation: math.gcd(a, b) takes a
and b
as arguments and returns their GCD. when it is called, it computes the GCD and directly returns the result.
This method repeatedly subtracts the smaller number from the larger one until both numbers become equal, resulting in the GCD.
Python
a = 60 # first number
b = 48 # second number
while a != b:
if a > b:
a -= b # subtract b from a if a is greater
else:
b -= a # subtract a from b if b is greater
print(a)
Explanation: while loop runs until a becomes equal to b. In each iteration, if a is greater than b, b is subtracted from a otherwise, a is subtracted from b. When both values become equal, that value is the GCD.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4