Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Algorithm design patterns
EXPERIMENT 53 / 66

Shrink the remainder.

Use a preserved mathematical quantity and a decreasing measure.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

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 THING THAT MUST STAY TRUE

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.

the_strategy.txt
REPLACE (a,b) with (b,a mod b) while b is nonzero
RETURN the remaining a

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

euclid.py
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))
↳ EXPECTED OUTPUT
6
9
0
  1. 1

    Normalising signs gives a nonnegative gcd. This implementation follows the conventional gcd(0,0)=0 result.

  2. 2

    Simultaneous assignment uses the old a and b for both right-hand expressions, preserving the intended recurrence.

  3. 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

TIME

O(log min(|a|, |b|)) remainder steps for positive inputs

SPACE

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

A SMALL MISSION

Use gcd to reduce the fraction 84/30.

Reveal one possible solution +
one_possible_solution.py
from math import gcd
numerator, denominator = 84, 30
divisor = gcd(numerator, denominator)
print(numerator // divisor, denominator // divisor)

06 Check your reasoning

QUICK SIGNAL CHECK

What decreases toward termination?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.