PrepStack · Markdown HTML

Sieve and prime factorization

Math, number theory, and combinatorics · HTML

Formal shape

A sieve marks multiples of each newly found prime p; SPF[x] stores the smallest prime divisor and supports repeated division.

Recognition signals

False friends

SignalWhy it is different
One enormous integerSieving to its square root may be infeasible; use a large-integer method.
Only the GCD of two valuesEuclid is direct and does not need full factors.

Core invariant

After processing prime p, its in-range multiples are marked; in SPF, the first factor written is the smallest prime factor.

State, transition, and processing order

ItemDefinition
StateAn is-prime or SPF array, current candidate p, and optionally a prime list.
TransitionAn unmarked p is prime; mark from p². For factorization, repeatedly divide x by SPF[x].
Frontier / orderCandidates increase, and all effects of prime factors below p have already propagated.

Python skeleton

def smallest_prime_factors(n):
    spf = list(range(n+1))
    if n >= 1: spf[1] = 1
    for p in range(2, int(n**0.5)+1):
        if spf[p] == p:
            for x in range(p*p, n+1, p):
                if spf[x] == x: spf[x] = p
    return spf

def factorize(x, spf):
    out = {}
    while x > 1:
        p = spf[x]
        out[p] = out.get(p, 0) + 1
        x //= p
    return out

Correctness sketch

  1. If p has no smaller prime mark, p is prime.
  2. Every p-multiple below p² already has a smaller factor, so starting at p² misses no new composite.
  3. Primes write SPF in increasing order, making the first writer minimal.
  4. Repeated division removes one prime factor at a time and reconstructs the original product.

Complexity

TimeSpaceParameters
O(n log log n) classic sieve; O(log x) per SPF factorizationO(n)preprocessing bound n and factored value x<=n

Edge cases

Error patterns

PatternWhy it fails / fix
Starting every mark at 2pCorrect but redundant; values below p² were handled earlier.
Treating one as primeInitialization must exclude it.
Overwriting SPF with larger factorsWrite only uninitialized entries.

Selection and exclusion rules

RelationTemplateBoundary

Original micro-example

PartDetail
Result28=2²×7.
ScenarioPrecompute through 30 and factor 28.
WalkthroughSPF[28]=2 twice, leaving 7 whose smallest factor is itself.

Recall prompts

My notes