← Back to libraryQuestion 77 of 273
⌨️Java CodingIntermediate

Find the GCD of Two Numbers

📌 Definition:

Compute the greatest common divisor of two integers (e.g. gcd(48, 18) = 6).

📖 Detailed Explanation:

Use the Euclidean algorithm: gcd(a, b) = gcd(b, a % b), repeating until b is zero, at which point a is the GCD. This is far faster than trial division — O(log(min(a, b))). The LCM follows as a * b / gcd(a, b).

💻 Solutions:
public static int gcd(int a, int b) {
    while (b != 0) { int t = b; b = a % b; a = t; }
    return a;
}
function gcd(a, b) {
  while (b !== 0) { [a, b] = [b, a % b]; }
  return a;
}
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
🔑 Key Points:
  • Euclidean algorithm: gcd(a,b) = gcd(b, a%b)
  • Base case: b == 0 -> return a
  • O(log(min(a,b)))
  • LCM = a*b / gcd
🌍 Real-World Example:

GCD reduces fractions, computes aspect ratios, and schedules repeating intervals — a small but genuinely reused primitive.

🎯 Scenario-Based Interview Question:

A candidate finds the GCD by looping from min(a,b) down to 1. Why is Euclid better?