Skip to contentKEEP THE CRAFTTHE SANCTUARY

Euclidean GCD

Compute a nonnegative greatest common divisor by replacing a divisor pair with a smaller equivalent pair. Follow remainder states, simultaneous assignment, zero inputs, and the arithmetic cost of large Python integers.

1 practice exercise1 interview problem

Recognize it when A fraction or integer ratio needs normalization by the largest shared factor.

Checking your account…

Euclidean GCD Code Labs

Replace a Pair Without Changing Divisors

The common divisors of a and b are exactly the common divisors of b and a modulo b. This identity lets Euclid replace the pair with a strictly smaller second value.

Reduce by Remainders

Repeat a, b = b, a mod b until b is zero. The terminal a is the greatest common divisor. Strict decrease proves termination; the stronger halving argument gives a logarithmic iteration bound: for r = a % b, either r <= b/2, or the next remainder is b % r = b - r < b/2. Thus within two reductions the current positive divisor b at least halves. If the original a is below b, first allow one swap-like reduction (a,b) -> (b,a); after that, b is the original smaller operand. This preliminary step and zero-input terminal work explain the constant term in the bound.

Trace Euclidean Remainders

Reference
def gcd_trace(a,b):
    a,b=abs(a),abs(b);trace=[]
    while b:trace.append([a,b,a%b]);a,b=b,a%b
    return trace
Practice

Implement gcd_trace(a,b). Normalize signs and return [a,b,a%b] until b becomes zero.

Public tests

  • Preserve common divisors across remainders

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Euclidean Remainders

def gcd_trace(a,b):
    a,b=abs(a),abs(b);trace=[]
    while b:trace.append([a,b,a%b]);a,b=b,a%b
    return trace

Follow Two Remainder Reductions

Predict the existing trace Lab for (35, 15). Its returned rows are the old pair and its remainder, not the gcd itself. The second call shows why an empty trace can still represent a valid nonzero gcd.

Step Executed statement State Why
Normalize a,b=abs(a),abs(b);trace=[] a=35, b=15, trace=[] Signs cannot change the set of positive common divisors.
First remainder trace.append([a,b,a%b]) trace=[[35, 15, 5]] 35 = 2*15 + 5, so the next pair has the same common divisors.
Replace old pair a,b=b,a%b a=15, b=5 Both right-hand expressions use the original pair.
Final remainder trace.append([a,b,a%b]);a,b=b,a%b trace=[[35, 15, 5], [15, 5, 0]], a=5, b=0 A zero remainder means 5 divides 15; the loop terminates before another modulo.
Zero-input call while b a=7, b=0, trace=[] The normalized terminal pair requires no recorded reductions.
Print Output
print(gcd_trace(35, 15)) [[35, 15, 5], [15, 5, 0]]
print(gcd_trace(-7, 0)) []

Use the trace to justify each replacement, then transfer the same invariant to gcd_many: each completed input extends the shared-divisor requirement. For a direct production calculation, Python math.gcd already supplies the integer contract.

Normalize Zero and Signs

Return a nonnegative gcd by taking absolute values. gcd(a, 0) is abs(a), and gcd(0, 0) is conventionally zero in programming libraries.

Compute GCD of Many Values

Reference
def gcd_many(values):
    result=0
    for value in values:
        a,b=result,abs(value)
        while b:a,b=b,a%b
        result=a
    return result
Practice

Implement gcd_many(values). Return the nonnegative greatest common divisor, with 0 for empty input.

Public tests

  • Fold normalized pairwise gcd

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute GCD of Many Values

def gcd_many(values):
    result=0
    for value in values:
        a,b=result,abs(value)
        while b:a,b=b,a%b
        result=a
    return result

Connect GCD to LCM and Fractions

Use lcm(a,b) = abs(a // gcd(a,b) * b), guarding the all-zero case and dividing before multiplication. GCD also reduces fractions and normalizes ratios.

Explain It in an Interview

Say: “Replacing (a,b) with (b,a mod b) preserves every common divisor while shrinking the second argument.” Trace one remainder sequence, normalize signs, and state the logarithmic remainder-iteration bound and the additional bit cost for large integers.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
One gcd pair: remainder iterationsO(1 + log(1 + min(abs(a), abs(b))))O(1 + log(1 + min(abs(a), abs(b))))Every two nonterminal reductions halve the current positive divisor b. If initial a<b, one preliminary reduction makes b the original smaller operand; zero cases and initialization add constant work.

Space

O(1) scalar slots for a single gcd; the trace Lab deliberately retains O(1 + log(1 + min(abs(a), abs(b)))) rows.

Assumptions

  • The iteration bound treats integer arithmetic as a unit operation. Python remainder cost also depends on operand bit length.
  • Folding m inputs performs m gcd reductions; the trace output is extra pedagogical storage.

Invariants Worth Saying Aloud

  1. Every divisor common to a and b also divides a - q*b, and the converse holds.
  2. After normalization, a and b are nonnegative; a % b is smaller than b whenever b is positive.
  3. At b = 0, the remaining a divides both original inputs and is their largest common divisor.

When To Use Or Avoid Euclidean GCD

Use It When

  • Find a shared integer factor without scanning every candidate divisor.
  • Fold many integers from gcd(0, x) = abs(x), retaining only the current gcd.

Choose Another Tool When

  • For all primes below a bound, use a sieve; gcd answers a different question.
  • A numeric approximation does not establish exact integer divisibility.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Returning a signed operand at the zero boundary

With (-9, 0), returning a directly gives -9 even though the gcd convention is nonnegative.

Prevent it: Normalize both inputs before the loop; an already terminal pair still needs sign normalization.

Avoid

result = a

Use instead

result = abs(a)

Overwriting the old dividend before computing its remainder

For (35, 15), sequential assignment changes a to 15, so a % b becomes zero and discards the actual remainder 5.

Prevent it: Compute both right-hand values from the old pair using simultaneous assignment.

Avoid

a = b
b = a % b

Use instead

a, b = b, a % b

Evaluating a remainder after the terminal state

When b is zero there is no next Euclidean transition. Taking a % b raises ZeroDivisionError.

Prevent it: Check the divisor before calculating the next remainder. The Lab uses while b for this reason.

Avoid

remainder = a % b

Use instead

remainder = None if b == 0 else a % b

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.