Back to Number Theory Dsa

Primes, Factorization & Divisor Structure

September 18, 2026 Wasil Zafar 8 min read

Understand prime structure and enumerate multiplicative objects efficiently.

Table of Contents

  1. Intuition, Vocabulary and Foundations
  2. Step-by-Step Derivations and Algorithms
  3. Implementation, Complexity and Engineering
  4. Applications, Case Studies and Exercises

Intuition, Vocabulary and Foundations

A prime is an integer greater than $1$ with exactly two positive divisors: $1$ and itself. Composite integers have additional divisors, while $1$ is neither prime nor composite. The Fundamental Theorem of Arithmetic says every $n>1$ has a unique representation

$$ n=p_1^{e_1}p_2^{e_2}\cdots p_k^{e_k} $$

apart from factor order. For example, $360=2^3\cdot3^2\cdot5$.

Every divisor of $360$ is $2^{f_1}3^{f_2}5^{f_3}$ with $0\le f_1\le3$, $0\le f_2\le2$, and $0\le f_3\le1$. Independent exponent choices give

$$ \tau(n)=\prod_{i=1}^{k}(e_i+1), $$

so $\tau(360)=24$. Summing each allowed prime power gives

$$ \sigma(n)=\prod_{i=1}^{k}\left(1+p_i+\cdots+p_i^{e_i}\right) =\prod_{i=1}^{k}\frac{p_i^{e_i+1}-1}{p_i-1}. $$

Thus $\sigma(360)=15\cdot13\cdot6=1170$. The proper-divisor sum is $\sigma(n)-n$ and classifies an integer as deficient, perfect, or abundant.

ConceptFormal meaningExampleBoundary or non-exampleQuestion answered
PrimeInteger $p>1$ with exactly two positive divisors$29$ is prime$1$ is neither prime nor compositeIs the integer indivisible?
CompositeInteger $n>1$ with a nontrivial divisor$35=5\cdot7$A prime has no such splitCan it be factored further?
FactorizationUnique $n=\prod p_i^{e_i}$$360=2^3\cdot3^2\cdot5$Reordering changes nothingWhich prime powers construct $n$?
DivisorPositive $d$ with $d\mid n$$24\mid360$$14\nmid360$Does $d$ divide exactly?
Prime exponentLargest $e$ with $p^e\mid n$$v_2(360)=3$Missing primes have exponent $0$How many copies of $p$ occur?
Divisor count$\tau(n)=\prod(e_i+1)$$\tau(360)=24$$\tau(1)=1$How many divisors exist?
Divisor sumProduct of prime-power geometric sums$\sigma(12)=28$Proper sum is $\sigma(n)-n$What do all divisors sum to?
Square-freeEvery exponent is at most $1$$30=2\cdot3\cdot5$$12$ is not square-freeDoes a squared prime divide $n$?

Step-by-Step Derivations and Algorithms

Trial division tests candidates in increasing order. When $p$ divides the current residual, divide repeatedly and record the exponent. The extracted prime powers times the residual always equal the original input.

If composite $m=ab$, at least one factor is no greater than $\sqrt m$; otherwise $ab>m$. To avoid overflow from $p^2$, use the equivalent condition

$$ p\le\frac{m}{p}. $$

Use the shrinking residual $m$, not only the original input. When the loop stops, any residual greater than $1$ is prime; otherwise it would possess a factor in the tested range.

After extracting $2$ and $3$, every larger prime is congruent to $1$ or $-1$ modulo $6$. Testing $6k\pm1$ candidates skips multiples of $2$ and $3$ but still requires divisibility checks.

Generate divisors incrementally. Begin with $[1]$; for each $p^e$, multiply existing partial divisors by $1,p,\ldots,p^e$. After each stage, the list contains exactly the divisors formed from processed primes.

Primes, Factorization & Divisor Structure algorithm map
flowchart TD
    A["Positive integer n"] --> B{"n equals 1?"}
    B -->|Yes| C["Empty factorization"]
    B -->|No| D["Extract powers of 2 and 3"]
    D --> E["Test 6k minus 1 and 6k plus 1"]
    E --> F{"Candidate within square-root bound?"}
    F -->|Yes| G["Extract complete exponent"]
    G --> E
    F -->|No| H{"Residual greater than 1?"}
    H -->|Yes| I["Record residual prime"]
    H -->|No| J["Factorization complete"]
    I --> J
    J --> K["Compute tau and sigma"]
    J --> L["Generate exponent combinations"]

Trial division preserves that extracted prime powers times the residual equal the original input and that the residual has no prime factor below the next candidate. It takes $O(\sqrt n)$ divisibility tests in the worst case, while listing divisors requires $\Theta(\tau(n))$ output work.

Implementation, Complexity and Engineering

This API accepts positive integers, returns the empty factorization for $1$, and rejects zero and negatives. Signed applications should store the sign separately rather than treating $-1$ as a positive prime.

It extracts $2$ and $3$, then alternates steps of $2$ and $4$ through $6k\pm1$. The overflow-safe condition compares the candidate with the residual divided by the candidate. Divisor statistics use exponents directly; generation occurs only when the divisor values are required.

from __future__ import annotations

from math import prod

Factorization = dict[int, int]


def factorize(n: int) -> Factorization:
    if n < 1:
        raise ValueError("factorization requires n >= 1")
    factors: Factorization = {}

    def extract(prime: int) -> None:
        nonlocal n
        exponent = 0
        while n % prime == 0:
            n //= prime
            exponent += 1
        if exponent:
            factors[prime] = exponent

    extract(2)
    extract(3)
    candidate, step = 5, 2
    while candidate <= n // candidate:
        extract(candidate)
        candidate += step
        step = 6 - step
    if n > 1:
        factors[n] = factors.get(n, 0) + 1
    return factors


def reconstruct(factors: Factorization) -> int:
    return prod(p**e for p, e in factors.items())


def divisor_count(factors: Factorization) -> int:
    return prod(e + 1 for e in factors.values())


def divisor_sum(factors: Factorization) -> int:
    return prod((p ** (e + 1) - 1) // (p - 1) for p, e in factors.items())


def generate_divisors(factors: Factorization) -> list[int]:
    divisors = [1]
    for prime, exponent in sorted(factors.items()):
        previous = divisors[:]
        power = 1
        for _ in range(exponent):
            power *= prime
            divisors.extend(value * power for value in previous)
    return sorted(divisors)


def is_square_free(factors: Factorization) -> bool:
    return all(exponent == 1 for exponent in factors.values())


def run_tests() -> None:
    cases = {
        1: {},
        2: {2: 1},
        29: {29: 1},
        360: {2: 3, 3: 2, 5: 1},
        7560: {2: 3, 3: 3, 5: 1, 7: 1},
        10403: {101: 1, 103: 1},
    }
    for number, expected in cases.items():
        factors = factorize(number)
        assert factors == expected
        assert reconstruct(factors) == number
        divisors = generate_divisors(factors)
        assert len(divisors) == divisor_count(factors)
        assert sum(divisors) == divisor_sum(factors)
        assert all(number % divisor == 0 for divisor in divisors)

    factors = factorize(360)
    assert divisor_count(factors) == 24
    assert divisor_sum(factors) == 1170
    assert is_square_free(factorize(30))
    assert not is_square_free(factorize(12))

    for invalid in (0, -1, -84):
        try:
            factorize(invalid)
        except ValueError:
            pass
        else:
            raise AssertionError("nonpositive input was not rejected")


if __name__ == "__main__":
    run_tests()
    print("all factorization and divisor tests passed")
ConcernFragile approachRobust approachComplexityFailure prevented
Input domainFactor zero or negatives silentlyRequire $n\ge1$$O(1)$ validationInfinite loops and ambiguity
Integer oneTreat $1$ as primeReturn the empty factorization$O(1)$Broken uniqueness
Stopping testUse $p^2\le n$ in fixed widthUse $p\le n/p$ on the residual$O(1)$ per candidateOverflow and excess work
CandidatesTest every integerExtract $2,3$, then test $6k\pm1$$O(\sqrt n)$ worst caseUnnecessary tests
ExponentsRecord a prime onceDivide until it no longer divides$O(e)$ for exponent $e$Lost multiplicity
Final residualDiscard itRecord it when greater than $1$$O(1)$Missing a large prime
Divisor countGenerate all divisorsCompute $\prod(e_i+1)$$O(k)$Avoidable output work
GenerationScan every integerExpand exponent choices$\Theta(\tau(n))$Full-range scan
Divisor sumAdd generated divisorsMultiply geometric sums$O(k)$Unnecessary enumeration

Applications, Case Studies and Exercises

Prime exponents turn structural questions into small combinatorial calculations. They reveal grid dimensions, sharding factors, scheduling periods, and multiplicative statistics without scanning every integer up to the input.

Practice

Apply Primes, Factorization & Divisor Structure

Case study 1 — Arrange 360 participants

  1. Factor $360=2^3\cdot3^2\cdot5$.
  2. Compute $\tau(360)=24$ possible row lengths.
  3. Pair each divisor $d$ with $360/d$.
  4. Conclude that there are $12$ unordered rectangles because $360$ is not a square.
  5. Generate the divisors and verify the result.

Success criterion: derive the count from exponents and confirm it by generation.

Case study 2 — Choose a production shard count

A system distributes $45{,}360$ records evenly across between $32$ and $256$ shards.

  1. Factor $45{,}360=2^4\cdot3^4\cdot5\cdot7$.
  2. Compute $\tau(45{,}360)=100$.
  3. Generate divisors and filter them to the permitted interval.
  4. For each candidate $d$, calculate the exact load $45{,}360/d$.
  5. Select using operational constraints such as worker count and memory.

Success criterion: produce every feasible shard count and verify exact divisibility.

Tiered exercises

  1. Recall: Classify $1,2,49,97$, and $221$.
  2. Factorization: Factor $7560$ and reconstruct it.
  3. Divisor count: Compute $\tau(7560)$ without listing divisors.
  4. Divisor sum: Derive $\sigma(72)$ from $72=2^3\cdot3^2$.
  5. Proof: Show that a number is a square exactly when every prime exponent is even.
  6. Debugging: Explain why a fixed original square-root bound may do excess work.
  7. Overflow: Replace $p^2\le n$ with an overflow-safe test.
  8. Implementation: Yield divisors lazily without sorting.
  9. Extension: Derive the number of square-free divisors.
  10. Benchmark: Compare odd-only trial division with the $6k\pm1$ wheel.

Use trial division for moderate individual inputs, exponent formulas when only statistics are needed, and output-sensitive generation when divisors themselves are required. Treat $1$, the final residual prime, overflow-safe stopping, and output size explicitly; the next topic extends these ideas to bulk prime and factor precomputation with sieves.

Next in the Series

In Sieves & Bulk Precomputation, we'll explore Precompute prime and factor information at scale..