Back to Number Theory Dsa

Analytic & Probabilistic Number Theory

September 22, 2026 Wasil Zafar 10 min read

Study average behavior, prime distribution, and probabilistic heuristics.

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

Analytic number theory studies arithmetic objects by measuring their collective behavior. Instead of asking whether one integer is prime, it asks how many primes lie below a large threshold. Instead of evaluating one divisor count, it studies the accumulated or average value across an interval. The perspective resembles traffic analysis: individual cars are irregular, but total flow can obey stable large-scale laws.

Let $\pi(x)$ denote the number of primes not exceeding $x$. The Prime Number Theorem states $\pi(x)\sim x/\log x$, meaning that the ratio approaches $1$ as $x\to\infty$. It suggests that a large integer near $x$ behaves heuristically like a prime with probability about $1/\log x$. For example, $\pi(100)=25$, while $100/\log 100\approx21.7$. The estimate is informative but not exact, especially for small inputs.

A summatory function converts an arithmetic function into a cumulative signal: $F(x)=\sum_{n\le x}f(n)$. Examples include the divisor summatory function $\sum_{n\le x}\tau(n)$ and the Mertens function $M(x)=\sum_{n\le x}\mu(n)$. An average order $g(n)$ describes the typical accumulated scale when $\sum_{n\le x}f(n)\sim\sum_{n\le x}g(n)$; it need not approximate every individual value.

Dirichlet series encode arithmetic sequences as $D_f(s)=\sum_{n=1}^{\infty}f(n)n^{-s}$. Multiplication of Dirichlet series corresponds to Dirichlet convolution where convergence permits. Dirichlet characters encode residue classes multiplicatively, and their orthogonality isolates congruence conditions. Probabilistic models supply useful predictions about prime searches, but a heuristic probability is not a proof about any specific integer.

ConceptDefinition or statementConcrete exampleNon-example or limitationQuestion answered
Prime-counting function$\pi(x)=\#\{p\le x:p\text{ prime}\}$$\pi(100)=25$$x/\log x$ is not the exact countHow many primes occur below $x$?
Prime Number Theorem$\pi(x)\sim x/\log x$Relative accuracy improves asymptoticallyIt gives no primality decision for one integerWhat is the large-scale density of primes?
Summatory function$F(x)=\sum_{n\le x}f(n)$$M(x)=\sum_{n\le x}\mu(n)$It does not preserve every pointwise valueHow much arithmetic mass accumulates by $x$?
Average orderSimpler function with matching summatory growth$\log n$ is an average-order scale for $\tau(n)$Most individual values need not be closeWhat is the typical aggregate scale?
Dirichlet series$\sum_{n\ge1}f(n)n^{-s}$$\zeta(s)=\sum_{n\ge1}n^{-s}$Formal manipulation outside convergence needs proofHow can convolution become multiplication?
Dirichlet characterPeriodic completely multiplicative function vanishing off units modulo $q$The nonprincipal character modulo $4$ distinguishes $1$ and $3$An arbitrary periodic function is not a characterHow can residue classes be selected algebraically?
Probabilistic prime modelPrime density near $x$ is about $1/\log x$Predicts about $\log x$ unrestricted trialsFilters change conditional densityHow many randomized attempts are expected?
Proven boundInequality valid over a stated rangeA certified upper bound for $\pi(x)$An asymptotic formula without an error termWhat resource limit can be guaranteed?

Step-by-Step Derivations and Algorithms

Partial summation is the discrete analogue of integration by parts. If $A(x)=\sum_{n\le x}a_n$, then for a differentiable weight $f$,

$$ \sum_{n\le x}a_n f(n)=A(x)f(x)-\int_1^x A(t)f'(t)\,dt, $$

with endpoint conventions adjusted to the application. It transfers information about an unweighted summatory function into a weighted sum, including estimates for weighted prime sums.

Character orthogonality acts as a residue-class filter. For reduced residues $a$ and $n$ modulo $q$, the normalized sum $\varphi(q)^{-1}\sum_{\chi\bmod q}\overline{\chi(a)}\chi(n)$ equals $1$ when $n\equiv a\pmod q$ and $0$ otherwise. This turns a congruence-restricted sum into character-twisted sums, provided nonunits and normalization are handled explicitly.

Harmonic decomposition exploits the fact that $\lfloor n/i\rfloor$ assumes only $O(\sqrt n)$ distinct values. If $q=\lfloor n/i\rfloor$, the quotient persists through $r=\lfloor n/q\rfloor$. An exact loop therefore processes $[i,r]$ at once and jumps to $r+1$.

For randomized prime generation, a $b$-bit odd candidate lies near $2^b$. The Prime Number Theorem gives density about $1/(b\log2)$ among all nearby integers and approximately twice that among odd candidates, leading to an expected $(b\log2)/2$ odd trials. This is a model-based expectation, not a hard upper bound.

Analytic & Probabilistic Number Theory algorithm map
flowchart TD
    A["State the arithmetic quantity"] --> B{"Exact or asymptotic goal?"}
    B -->|Exact| C["Build a summatory identity"]
    C --> D{"Repeated floor quotients?"}
    D -->|Yes| E["Use harmonic blocks"]
    D -->|No| F["Use sieve or direct summation"]
    B -->|Asymptotic| G["Choose analytic encoding"]
    G --> H{"Residue restriction?"}
    H -->|Yes| I["Apply character orthogonality"]
    H -->|No| J["Use partial summation or Dirichlet series"]
    E --> K["Verify with an exact oracle"]
    F --> K
    I --> L["Attach theorem and error regime"]
    J --> L
    L --> M["Label guarantees and heuristics"]

Harmonic grouping maintains that every index below the current pointer has been processed exactly once while every index in the next block shares one quotient. Since $\lfloor n/i\rfloor$ changes only $O(\sqrt n)$ times, the exact algorithm uses $O(\sqrt n)$ blocks and $O(1)$ auxiliary space.

Implementation, Complexity and Engineering

The reference implementation builds an exact sieve oracle, compares $\pi(x)$ with elementary asymptotic estimates, evaluates the divisor summatory function directly and by harmonic grouping, and verifies character orthogonality for the two real characters modulo $4$. Returned labels distinguish exact values from heuristic estimates.

Floating-point formulas are used only for estimates. They never determine primality or an exact arithmetic answer. Large-input systems should record the range of every explicit bound, avoid unstable subtraction, and use higher precision when required by the error budget.

from math import isqrt, log


def prime_table(limit):
    if limit < 0:
        raise ValueError("limit must be nonnegative")
    sieve = bytearray(b"\x01") * (limit + 1)
    sieve[0] = 0
    if limit >= 1:
        sieve[1] = 0
    for prime in range(2, isqrt(limit) + 1):
        if sieve[prime]:
            start = prime * prime
            sieve[start : limit + 1 : prime] = b"\x00" * (
                (limit - start) // prime + 1
            )
    return sieve


def prime_count_prefix(limit):
    sieve = prime_table(limit)
    prefix = [0] * (limit + 1)
    count = 0
    for value in range(limit + 1):
        count += sieve[value]
        prefix[value] = count
    return sieve, prefix


def prime_count_estimates(x):
    if x < 2:
        return {"kind": "heuristic asymptotic", "pnt": 0.0, "second_order": 0.0}
    lx = log(x)
    return {
        "kind": "heuristic asymptotic",
        "pnt": x / lx,
        "second_order": x / lx + x / (lx * lx),
    }


def divisor_summatory_direct(n):
    if n < 0:
        raise ValueError("n must be nonnegative")
    return sum(n // divisor for divisor in range(1, n + 1))


def divisor_summatory_harmonic(n):
    """Return sum_{d <= n} floor(n / d) in O(sqrt(n)) blocks."""
    if n < 0:
        raise ValueError("n must be nonnegative")
    total = 0
    left = 1
    blocks = []
    while left <= n:
        quotient = n // left
        right = n // quotient
        total += quotient * (right - left + 1)
        blocks.append((left, right, quotient))
        left = right + 1
    return total, blocks


def chi_mod_4(kind, value):
    residue = value % 4
    if residue % 2 == 0:
        return 0
    if kind == "principal":
        return 1
    if kind == "odd":
        return 1 if residue == 1 else -1
    raise ValueError("unknown character")


def character_filter_mod_4(value, target):
    if target not in (1, 3):
        raise ValueError("target must be 1 or 3 modulo 4")
    total = sum(
        chi_mod_4(kind, target) * chi_mod_4(kind, value)
        for kind in ("principal", "odd")
    )
    return total // 2


def expected_odd_trials_for_b_bit_prime(bits):
    if bits < 2:
        raise ValueError("bits must be at least 2")
    return bits * log(2) / 2


sieve, pi = prime_count_prefix(100)
assert pi[10] == 4
assert pi[100] == 25
assert [i for i, flag in enumerate(sieve) if flag][:6] == [2, 3, 5, 7, 11, 13]

exact = divisor_summatory_direct(100)
grouped, blocks = divisor_summatory_harmonic(100)
assert exact == grouped == 482
assert blocks[0] == (1, 1, 100)
assert blocks[-1] == (51, 100, 1)
assert len(blocks) <= 2 * isqrt(100)

for value in range(1, 40):
    assert character_filter_mod_4(value, 1) == int(value % 4 == 1)
    assert character_filter_mod_4(value, 3) == int(value % 4 == 3)

estimates = prime_count_estimates(100)
assert 21 < estimates["pnt"] < 22
assert expected_odd_trials_for_b_bit_prime(2048) > 700

try:
    divisor_summatory_harmonic(-1)
    raise AssertionError("negative input was accepted")
except ValueError:
    pass

print("all tests passed")
MethodOutput typeTime and spaceValidity regimeFailure modeMitigation
Sieve prime countExact$O(n\log\log n)$ time and $O(n)$ spaceBounded intervalMemory exhaustionUse odd-only or segmented sieves
$x/\log x$Asymptotic estimate$O(1)$ arithmeticLarge positive $x$Treating it as exactLabel it and compare with explicit bounds
Partial summationExact identity plus imported estimatesDepends on the summatory boundRegularity assumptions must holdDropping boundary or error termsPropagate endpoints and errors explicitly
Character orthogonalityExact finite identity$O(\varphi(q))$ in direct formMatching residues and charactersMishandling nonunitsDefine values and normalization explicitly
Harmonic decompositionExact$O(\sqrt n)$ blocks, $O(1)$ auxiliary spaceFloor-quotient sumsWrong block endpointVerify the endpoint formula against an oracle
Prime-density modelHeuristic expected trials$O(1)$ estimateUniform candidates near a scaleIgnoring candidate filtersUse the conditional density
Geometric tail modelProbabilistic estimate$O(1)$ per calculationApproximately independent trialsTreating expectation as a deadlineAdd operational retry limits
Empirical experimentObservationDepends on sample countSampled generator and rangeUnjustified extrapolationReport seed, sample size, and range

Applications, Case Studies and Exercises

Analytic estimates help size prime tables, predict randomized search work, and select between exact and asymptotic methods. Their practical value depends on disciplined labels: exact harmonic decomposition can produce a production answer, while a Prime Number Theorem estimate may guide capacity planning but cannot replace validation.

Practice

Apply Analytic & Probabilistic Number Theory

Case study 1 — inspect prime density. Build exact values of $\pi(x)$ for $x=10^2,10^3,10^4,10^5,$ and $10^6$. Compare them with $x/\log x$ and $x/\log x+x/(\log x)^2$. Record absolute and relative errors. Checkpoint: confirm that the basic ratio trends toward $1$ overall without claiming monotonic improvement. Success means exact counts come from the sieve and estimates remain labeled.

Case study 2 — budget randomized prime generation. For $b=256,1024,$ and $2048$, estimate the expected odd-candidate count using $(b\log2)/2$. Simulate sampling with a fixed seed and deterministic primality testing, then compare trial counts over many runs. Record the candidate filter, mean, median, and upper percentiles. Success means the density heuristic, measurements, and any hard retry policy remain distinct.

Hands-on arithmetic-sum exercise. Compute $\sum_{d\le n}\lfloor n/d\rfloor$ for every $n\le1000$ by direct summation and harmonic blocks. For $n=10^6$, record the block count and verify it is at most $2\lfloor\sqrt n\rfloor$. Explain why the sum counts ordered pairs $(a,b)$ satisfying $ab\le n$. Success means exact oracle agreement without looping over all divisors in the optimized method.

Tiered follow-up. Recall: distinguish pointwise value, summatory function, and average order. Derive: prove the harmonic-block endpoint. Implement: use character orthogonality to count a reduced residue class. Debug: explain why the unrestricted density underestimates density among odd candidates by about two. Extend: apply partial summation to an assumed estimate for $\pi(x)$ while carrying its error term symbolically.

Use exact sieves and summatory algorithms when correctness requires a value, explicit bounds when resources need guarantees, asymptotic formulas for large-scale comparison, and probabilistic models for expectations that will still be verified. Always state the limiting variable, candidate distribution, error term or absence of one, and whether a claim is proved, conditional, heuristic, or empirical.