AlgoViz

GCD & LCM

easy 14 min

The GCD is the largest number that divides two numbers; the LCM is the smallest number both divide.

See it run

Watch Euclid shrink (48, 18) to 6 in three divisions, a 6 × 4 rectangle tile perfectly with 2 × 2 squares, two bus schedules meet at minute 36, and see why Euclid never needs more than a few dozen steps.

Operations

Euclidean Algorithm

Replace $(a, b)$ with $(b, a \bmod b)$ until $b = 0$; the last non-zero value is the GCD. Here we find $\gcd(48, 18)$, then get the LCM from it.

Step 1 of 7

Find gcd(48, 18)

  1. 48a
  2. 18b
  3. 12
  4. 6
  5. 0
a = 48b = 18a mod b = 12steps = 0

We want the largest number that divides both 48 and 18. Euclid's rule says \gcd(a, b) = \gcd(b, a \bmod b), so we keep replacing the pair until [b] becomes 0. The value left in a is the answer.

Step 1: Find gcd(48, 18)

def gcd(a, b):    steps = 0    while b != 0:        r = a % b          # remainder        a, b = b, r        # slide the pair        steps += 1    return a, stepsprint(gcd(48, 18))         # (6, 3)print(48 // 6 * 18)        # 144, the LCM
Time
O(log min(a, b))
Space
O(1)
try every divisor
O(min(a, b))
recursive version
O(log min(a, b)) stack

The whole algorithm is one line inside a loop: a, b = b, a % b. Memorise it as replace and repeat until b is 0.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Multiplying before dividing in the LCM

    major

    a * b can overflow a 32-bit or 64-bit integer even when the LCM itself fits. Python integers never overflow, but the habit breaks Java, C++ and JavaScript code. Divide by the GCD first.

    Wrong
    def lcm(a, b):    return a * b // gcd(a, b)   # a * b may overflow elsewhere
    Right
    def lcm(a, b):    return a // gcd(a, b) * b   # stays as small as the answer
  • Updating a and b in the wrong order

    critical

    Writing the two assignments separately overwrites a before a % b is computed, so the algorithm computes the wrong remainder or divides by zero.

    Wrong
    while b:    a = b    b = a % b      # a is already b, so this is always 0
    Right
    while b:    a, b = b, a % b    # both computed from the old values
  • Dividing by zero instead of stopping

    critical

    The loop must test b before using it as a divisor. gcd(n, 0) is n, so b = 0 is the stopping signal, not a value to divide by.

    Wrong
    def gcd(a, b):    while a % b != 0:     # crashes when b == 0        a, b = b, a % b    return b
    Right
    def gcd(a, b):    while b != 0:        a, b = b, a % b    return a              # gcd(n, 0) == n
  • Ignoring negative inputs

    minor

    Python's % takes the sign of the divisor, so the hand-written loop returns -6 for gcd(12, -18). The GCD is defined as positive; take absolute values or use math.gcd, which always returns a non-negative result.

    Wrong
    gcd(12, -18)   # -6 with the plain loop
    Right
    def gcd(a, b):    a, b = abs(a), abs(b)    while b:        a, b = b, a % b    return a           # 6
  • Using the product as the LCM of a list

    major

    The product of all numbers is a common multiple but rarely the least one. For [4, 6, 8] the product is 192 while the LCM is 24. Fold the two-number LCM across the list.

    Wrong
    from math import prodanswer = prod([4, 6, 8])      # 192
    Right
    from functools import reduceanswer = reduce(lambda x, y: x // gcd(x, y) * y, [4, 6, 8])   # 24
  • Trying every divisor

    major

    Counting down from min(a, b) is O(min(a, b)): a billion steps for big inputs. Euclid gives the same answer in at most a few dozen divisions.

    Wrong
    for d in range(min(a, b), 0, -1):    if a % d == 0 and b % d == 0:        return d
    Right
    while b:    a, b = b, a % breturn a

Interview tips

  • Spot it fast

    • Reduce a fraction, or check whether two numbers share a factor: GCD.
    • When do repeating events line up again: LCM.
    • Largest equal piece, tile or group size that divides everything: GCD.
    • A value reachable as ax + by (jugs, steps of two sizes): a multiple of gcd(a, b).
  • Know cold

    • gcd(a, b) = gcd(b, a mod b), and gcd(a, 0) = a.
    • lcm(a, b) = a / gcd(a, b) × b.
    • gcd(a, b) × lcm(a, b) = a × b for positive a and b.
    • Coprime means gcd = 1, and then lcm = a × b.
  • Say it in the interview

    • "Any common divisor of a and b also divides a - qb, which is a mod b, so the GCD is unchanged."
    • "a mod b is less than a / 2, so the larger number halves every two steps: O(log min(a, b))."
    • Mention math.gcd and math.lcm in Python, std::gcd in C++17, and dividing first to avoid overflow.
  • Traps

    • gcd(0, 0) is 0 by convention, so lcm(0, 0) would divide by zero: return 0 when either input is 0.
    • Negative inputs give negative results with a plain % loop in Python.
    • The LCM of a list is not the product of the list.