Learn
Euclidean Algorithm for GCD
The Greatest Common Divisor (GCD), also known as the Greatest Common Factor (GCF) or Highest Common Factor (HCF), is the largest number that divides both inputs. The Euclidean algorithm computes GCD efficiently using the property .
Any common divisor of and also divides . So you preserve the GCD through the modulo operation. Eventually, you reach .
text
function gcd(a, b):
while b != 0:
temp = b
b = a mod b
a = temp
return a
Recursive version:
text
function gcd(a, b):
if b == 0:
return a
return gcd(b, a mod b)
Example trace: Return
Applications: You use GCD for simplifying fractions, cryptography (RSA), finding LCM, and solving Diophantine equations.
Time complexity: because the remainder decreases by at least half every steps.
Space complexity: for iterative, for recursive due to call stack.