PrepStack · Markdown HTML

Modular arithmetic and fast power

Math, number theory, and combinatorics · HTML

Formal shape

If a≡b (mod M), addition and multiplication preserve congruence; binary exponentiation multiplies powers base^(2^k) selected by exponent bits.

Recognition signals

False friends

SignalWhy it is different
Exact quotient or magnitude comparisonReduction loses scale and cannot recover original ordering.
Using Fermat inverses unconditionallya^(M-2) needs prime M and nonzero a modulo M.

Core invariant

During binary power, result*base^exp remains congruent to the original target; each step consumes one bit.

State, transition, and processing order

ItemDefinition
Stateresult, current base, remaining exponent, and modulus.
TransitionIf the low bit is one, multiply base into result; square base modulo M and halve the exponent.
Frontier / orderUnprocessed high exponent bits form the frontier; each iteration removes the lowest bit.

Python skeleton

def mod_pow(base, exp, mod):
    if mod <= 0 or exp < 0:
        raise ValueError
    result = 1 % mod
    base %= mod
    while exp:
        if exp & 1:
            result = result * base % mod
        base = base * base % mod
        exp >>= 1
    return result

def prime_mod_inverse(a, p):
    if a % p == 0: raise ZeroDivisionError
    return mod_pow(a, p-2, p)

Correctness sketch

  1. A nonnegative exponent is a sum of selected powers of two.
  2. When its low bit is one, current base is exactly the corresponding power.
  3. Squaring and shifting preserve the result*base^exp invariant.
  4. At exp=0, result is the target power modulo M.

Complexity

TimeSpaceParameters
O(log exp)O(1)nonnegative exp and positive modulus mod

Edge cases

Error patterns

PatternWhy it fails / fix
Reducing only at the endIntermediates become huge or overflow.
Ignoring inverse preconditionsA nonunit has no modular inverse.
Taking division modulo M directlyModular division means multiplying by an existing inverse.

Selection and exclusion rules

RelationTemplateBoundary
large-count supportCombinatorial counting / inclusion-exclusionCounts use a modulus and inverses
number-theory compositionSieve and prime factorizationPrime moduli and inverses use factor properties

Original micro-example

PartDetail
ResultThe result is 5.
ScenarioCompute 3^13 mod 7.
Walkthrough13 is binary 1101; multiply only selected repeated squares and reduce at every step.

Recall prompts

My notes