PrepStack · Markdown HTML

GCD / LCM and divisibility

Math, number theory, and combinatorics · HTML

Formal shape

gcd(a,b)=gcd(b,a mod b); lcm(a,b)=|a/gcd(a,b)*b|; values ax+by are exactly multiples of gcd(a,b).

Recognition signals

False friends

SignalWhy it is different
Full prime exponents are requiredGCD summarizes common factors; factorize when individual exponents matter.
Approximate real-valued ratiosGCD is exact integer arithmetic; floating-point comparisons need an error model.

Core invariant

Each Euclidean step preserves the set of common divisors while the second argument strictly decreases to zero.

State, transition, and processing order

ItemDefinition
StateThe current integer pair (a,b), plus a sign convention for normalization.
TransitionRepeat (a,b)=(b,a%b); on termination |a| is the GCD.
Frontier / orderThe remainder carries the common-factor information not yet eliminated and decreases numerically.

Python skeleton

def gcd(a, b):
    a, b = abs(a), abs(b)
    while b:
        a, b = b, a % b
    return a

def lcm(a, b):
    return 0 if a == 0 or b == 0 else abs(a // gcd(a,b) * b)

def normalize_ratio(x, y):
    if y == 0: return (1 if x > 0 else -1 if x < 0 else 0, 0)
    if y < 0: x, y = -x, -y
    g = gcd(x, y)
    return (x // g, y // g)

Correctness sketch

  1. Every divisor of a and b also divides a-qb=a%b.
  2. Every divisor of b and the remainder also divides a, so common divisors are preserved.
  3. Remainders decrease, ending at (g,0).
  4. Dividing a ratio by g yields a unique form under a fixed sign convention.

Complexity

TimeSpaceParameters
O(log min(|a|,|b|))O(1)integer inputs a and b; fold the operation for many values

Edge cases

Error patterns

PatternWhy it fails / fix
Multiplying before LCM divisionThis can overflow; divide by gcd first.
Inconsistent signsEquivalent ratios become different keys.
Floating-point division for ratio keysPrecision and zero denominators break equivalence.

Selection and exclusion rules

RelationTemplateBoundary
number-theory compositionModular arithmetic and fast powerModular inverses or extended Euclid appear
structural refinementSieve and prime factorizationPrime exponents are needed beyond one gcd

Original micro-example

PartDetail
ResultThe canonical direction is (-2,3).
ScenarioNormalize direction vector (-6,9).
Walkthroughgcd(6,9)=3; divide both components while keeping the chosen sign convention.

Recall prompts

My notes