Shrink the remainder.
Use a preserved mathematical quantity and a decreasing measure.
01 Model the idea
The Euclidean algorithm repeatedly replaces (a, b) with (b, a mod b). Their common divisors do not change under that transformation. The second nonnegative value strictly decreases until it reaches zero, providing termination. The remaining first value is the greatest common divisor, which can simplify fractions and support number-theoretic algorithms.
The pair’s set of common divisors is preserved.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
REPLACE (a,b) with (b,a mod b) while b is nonzero
RETURN the remaining a03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def gcd(a, b):
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
return a
print(gcd(84, 30))
print(gcd(0, 9))
print(gcd(0, 0))6 9 0
- 1
Normalising signs gives a nonnegative gcd. This implementation follows the conventional gcd(0,0)=0 result.
- 2
Simultaneous assignment uses the old a and b for both right-hand expressions, preserving the intended recurrence.
- 3
The number of remainder steps is logarithmic in the smaller positive magnitude. Arbitrarily large integer division has its own bit-complexity cost; treating each modulo as constant time is a model assumption.
04 Count the cost
O(log min(|a|, |b|)) remainder steps for positive inputs
O(1) integer variables; integer bit size still matters
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Use gcd to reduce the fraction 84/30.
Reveal one possible solution +
from math import gcd
numerator, denominator = 84, 30
divisor = gcd(numerator, denominator)
print(numerator // divisor, denominator // divisor)06 Check your reasoning
What decreases toward termination?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.