GCD with Euclidean Algorithm
Given two non-negative integers a and b, compute their greatest common divisor (GCD) using the Euclidean algorithm. The GCD is the largest positive integer that divides both numbers without a remainder.
For example, GCD(12, 8) = 4 because 4 divides both 12 and 8, and no larger number does. GCD(7, 3) = 1 because 7 and 3 share no common factors (they are coprime). GCD(0, 5) = 5 because every number divides 0, and the GCD of 0 and any non-zero number is that number.
The Euclidean algorithm is one of the oldest known algorithms, dating back to ancient Greece (circa 300 BC). It is remarkably elegant: repeatedly replace the larger number by its remainder when divided by the smaller number, until one of them reaches zero. The non-zero number at that point is the GCD.
The Euclidean algorithm is far more efficient than factoring both numbers and comparing prime factors. It runs in O(log min(a, b)) time, which is fast even for numbers with hundreds of digits. This algorithm is foundational for cryptography (RSA key generation), rational number arithmetic (simplifying fractions), and many number-theoretic computations.
Edge cases include one or both numbers being zero (GCD(x, 0) = x), and both numbers being equal (GCD(x, x) = x). The algorithm handles all of these naturally.
Example Input & Output
100/10
Same numbers
Prime pair
GCD of 12 and 8 is 4
GCD with 0
Algorithm Flow
Solution Approach
Implement the Euclidean algorithm: repeatedly replace the larger number with the remainder of division by the smaller number.
The loop runs while b is not zero. Inside, store b in a temporary variable t, set b to a % b (remainder), and set a to t (the old b). When b reaches 0, a holds the GCD. For example, with a=12, b=8: first iteration: t=8, b=12%8=4, a=8. Second: t=4, b=8%4=0, a=4. Return 4.
Many languages provide a built-in GCD function: Python's math.gcd, Java's BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)), or Rust's a.gcd(&b). The manual implementation using the Euclidean algorithm is shown here for educational purposes.
Time complexity is O(log min(a, b)). Space complexity is O(1).
Best Answers
class Solution {
public int solution(int a, int b) {
while(b!=0){int t=b;b=a%b;a=t;}return a;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
