Initialize a mutable endpoint array to the inclusive cumulative counts . Scan input array indices . For each complete sorting record with sort key , first decrement , then write at output array index . This is equivalent to writing at the old endpoint minus one and then decrementing the endpoint.[ref]
In the worked example, the first input sorting record read is at array index six. Its endpoint changes from to , so the complete sorting record goes to . Next, changes from seven to six and goes to . Writing before the decrement at the old endpoint would put outside its reserved integer interval and try to put beyond the output array. All seven writes are:
Each endpoint changes only when a sorting record with its own sort key is placed. Consequently, stays at five through the placements of before dropping to four for .
Figure 1.
A backward input scan gives forward order among equal sort keys
. Original complete trace of the seven-sorting record example. Each row shows the endpoint decrement and resulting output array; the newly written complete sorting record is dark. Both input and output array indices start at zero. The final order is . Details.
Here is a complete implementation under the stated input contract; each sorting record is a pair whose first component is its integer sort key:
def counting_sort_records(records, K):
    end = [0] * K
    output = [None] * len(records)
    for key, data in records:
        end[key] += 1
    for key in range(1, K):
        end[key] += end[key - 1]
    for i in range(len(records) - 1, -1, -1):
        key = records[i][0]
        end[key] -= 1
        output[end[key]] = records[i]
    return output
The same array end successively stores frequencies, inclusive cumulative counts, and moving exclusive endpoints; the formulas describe their mathematical values without requiring three stored arrays. The write copies the complete sorting record, including its associated data. In particular, two occurrences of an identical pair still cause two separate writes.
For a short algorithm correctness proof, let be the number of already placed sorting records with sort key . A loop invariant is
All integer intervals here mean output array indices. Initially , so each whole reserved integer interval is unfilled. When the next sorting record has sort key , fewer than such occurrences have been placed, giving . Decrementing selects a fresh slot inside its reserved integer interval. At termination, and : every output slot has been filled exactly once with a complete input occurrence. The disjoint, increasing sort key ranges establish sortedness, while the fresh-slot property establishes sorting permutation preservation.
For stable sorting, take two input occurrences with equal sort keys at array indices . The backward scan visits first and puts it farther right in their shared integer interval. When is visited, the endpoint has decreased at least once, so its output position is smaller. Thus their original order survives. A forward scan with this same decrement rule reverses every equal-sort key group: it would put at positions five, four, three. A forward scan can instead be stable if it starts from and fills each integer interval left to right, incrementing after each write. The scan direction and endpoint convention must agree.
Count initialization takes writes, output initialization takes writes, counting takes updates, the prefix sum pass takes updates, and placement takes writes. Hence time complexity and auxiliary storage are in Big O notation, assuming constant-cost sort key access, integer arithmetic, array indexing and complete sorting record movement. Large records can instead be represented by constant-size references.[ref]
For example, three sorting records with sort keys zero, and zero require one million counters if ; unused sort keys still incur initialization and prefix sum work. The bound is therefore linear in the input length only when . Empty input skips the record scans, but this implementation still initializes counters and accumulates their prefix sums. For nonempty input, counting all records and filling their ranges gives a concrete termination argument.
Direct sort key indexing is a different operation from a binary comparison. The comparison sorting lower bound concerns comparison sorts; counting sort uses its restricted integer sort keys as array indices. Its small- speed is particularly useful for categorical numerical labels and for each stable sorting pass of radix sort: the reserved integer intervals turn group sizes into exact destinations.
Stars and bars counts tuples of nonnegative integers with a prescribed sum. For integers and , its statement is
Such a tuple is a weak composition of an integer. Think of labelled bins: counts identical objects in the first bin, in the second, and so on. Bin names distinguish positions even when counts agree. Stars and bars counts these count tuples; assigning individually distinct objects requires additional information. [ref]
Computed example. With and , the number of weak compositions of an integer is . The string ••|•|•• encodes : two dots before the first bar, one between the bars, and two after the second. For a fixed first-bin count , the second-bin count can be any integer from to and the third is forced. Thus the direct count is .
Figure 1.
Stars and bars for five identical objects and three labelled bins: ordinary splits, adjacent bars, and bars at either end
. Details.
Adjacent bars encode an empty middle bin: ••||••• gives . A bar at the left end encodes an empty first bin, as in |••|••• for ; a bar at the right end encodes an empty third bin, as in ••|•••| for . These are valid weak compositions of an integer. For every count is zero, and for the unique tuple is , consistent with .
Proof outline. Replace each count by that many dots and separate successive groups with bars. Reading the group sizes reverses this construction, so it is a bijection between weak compositions of an integer and strings of dots and bars. Choose the bar positions among positions; the binomial coefficient counts the choices. The beauty is that empty bins need no separate cases: end bars and adjacent bars encode them automatically.
If every bin must be nonempty, the tuples are compositions of an integer, and their count is for ; for there are none. Subtract one from every count, setting . This is a bijection to weak compositions of an integer of , so stars and bars gives . For five objects and three bins, this is , with the six positive tuples
For instance, shifts to , whose sum is . Sorting the six positive tuples collapses them to just two integer partitions, and . Thus named bins and unordered summands answer different questions.
Stars and bars is useful for allocating identical resources or enumerating integer solutions without listing them individually. Prescribed lower bounds can be subtracted just like the nonempty-bin requirement. Upper bounds require removing forbidden tuples; the existing bounded weak compositions article applies the inclusion-exclusion principle to those violations.
Stateful channel iteration and Fibonacci numbers Created 2026-10-25 Updated 2026-10-31
Consider a component that remembers its previous input and maps input to , then sets . Feeding each output back into the same component gives state transition . Starting at , the successive outputs are , the Fibonacci numbers after calls. The state transition, rather than a memoryless function on one integer, explains the recurrence. Replacing the component between calls or repeatedly feeding a fixed external input gives different behavior.
Stirling formula Created 2026-09-24 Updated 2026-10-14
Stirling's formula turns the long product defining a factorial into a short expression. For positive integers , put
Then as . This is asymptotic equivalence: , so the relative error tends to zero. It does not say that the absolute error tends to zero, and the formula is not an equality for finite . The Gamma function extends this approximation beyond integer inputs. [ref]
For ,
The leading estimate is about low. Multiplying by the first correction factor gives
which is about low. The Stirling correction by Gaussian moments explains why this factor is rather than an arbitrary numerical adjustment.
Figure 1.
Relative factorial errors shrink faster after the first Stirling correction
. For each integer , the curves compare and with the exact factorial. The vertical axis is the nonnegative relative error, on a logarithmic scale. Details.
The usefulness is in ratios as well as in enormous numbers. Applying Stirling's formula to the three factorials in a central binomial coefficient gives
This counts the ways to choose exactly half of objects. Equivalently, for independent fair coin tosses, the binomial distribution assigns probability to exactly heads. An exponentially large count becomes a simple probability scale after cancellation.
For numerical calculations, taking the natural logarithm yields
where . Computing a logarithm of a large factorial avoids representing the factorial itself. The Robbins bounds for Stirling's formula give a finite- interval for this logarithmic remainder, rather than only a limiting statement.
The factor is beautiful because a Gaussian integral lies behind a discrete product. The Gaussian peak behind Stirling's formula displays this connection through the Gamma integral and Laplace's method. A rigorous proof must also control the tails of the integral; the local expansion explains the geometry but is not by itself a complete proof.
James Stirling published Methodus differentialis in 1730, a treatise on summation and interpolation of infinite series. This setting connects the formula with a practical calculation problem: taking logarithms turns a long product into a sum, whose growth can be approximated. [ref]
The Hamming number stream merges its shared multiples by two, three and five. To emit its first values, each of the fixed number of mapped streams and merge nodes advances at most positions. With lazy evaluation that shares each evaluated list cell, this takes comparisons and fixed-factor multiplications. The statement counts arithmetic operations, rather than bits: the growing exact integers make their bit-operation costs larger. Recomputing independent copies of the recursively defined stream loses this sharing argument.
Strong induction Created 2026-09-24 Updated 2026-10-18
Strong induction establishes a proposition for all integers . Prove ; then, for each , assume every with and prove . The induction hypothesis includes all earlier cases, so the inductive step can use whichever smaller indices it needs. It cannot use itself.[ref]
This is useful when a construction breaks into smaller pieces of varying sizes. A prime factorization splits a composite number into smaller integer divisors, which need not be one less than the original integer. A recursive procedure can likewise call itself on several smaller inputs. The available cases should match those dependencies. Strong induction lets the mathematical proof follow the construction rather than forcing every step through the immediately preceding size.
Every integer has a prime factorization. The induction base case is prime. For a larger integer, either it is prime or it is , with . The induction hypothesis supplies prime factorizations of both smaller integer divisors; multiplying them gives one for . This proves existence, while uniqueness requires the additional argument under the fundamental theorem of arithmetic.[ref]
For the chosen number , one possible recursive decomposition is
The step at needs results for and , rather than a result for . Each composite number in this factorization tree splits into strictly smaller positive integers, so recursive descent terminates at prime numbers. The tree describes one construction; another choice of integer divisors can give a differently shaped factorization tree.
Figure 1.
The step for 84 can use 6 and 14: the induction hypothesis covers both
. Original factorization tree , followed by and . Arrows show recursive dependencies toward smaller integers, rather than the order of increasing induction. The strip at the bottom marks the earlier cases available at the step for , with the required and highlighted. No use of the unproved case is permitted in the hypothesis. Details.
The same pattern explains the usefulness of strong induction for algorithm correctness. When a recursive procedure returns answers for smaller inputs, the induction hypothesis can justify those answers; the remaining task is to justify how the current call combines them. Strictly decreasing a nonnegative integer size measure establishes termination. Correctness also requires each call's conditions and its combination rule; termination alone does not make an algorithm correct.
Sturmian word 2026-10-20
An infinite binary word is Sturmian if it has exactly distinct contiguous subwords of length for every positive integer .
Subadditivity of the base-p digit sum Created 2026-09-28 Updated 2026-10-18
For nonnegative integers and an integer base ,
In column addition, every arithmetic carry replaces units in one numeral digit by one unit in the next position and therefore decreases the base-p digit sum by . Count each outgoing carry separately, including each step of a chain. There is equality precisely when there are no carries. For prime number bases, Kummer's theorem turns this digit-sum deficit into a prime exponent.
Fix a real angle fraction , and repeatedly multiply by in the circle group. The generated cyclic subgroup is . Equivalently, the angle fractions are the fractional parts of , with one full turn identified with zero.
If is a rational number in lowest terms, with and coprime, then and no smaller positive power is . Hence is a finite cyclic group of order , consisting of equally spaced points. For , the successive angle fractions, starting at , are
The subgroup is finite, so it is a closed subgroup of the circle group; it is also a discrete subgroup. It is not an open subgroup, since every ambient neighbourhood of any of its points contains an arc, rather than only these seven points.
If is an irrational number, no nonzero integer satisfies , so the powers never repeat. The stronger statement is that is a dense set in the circle group: every nonempty open arc contains a power . Thus its closure is all of , while itself is a countable proper subgroup and is not a closed subgroup or a discrete subgroup. See irrational rotation and everywhere interval frequency under an irrational rotation for the corresponding motion and its long-term frequencies.
For , direct computation of the fractional parts of gives, to six decimal places,
For example, and . These calculations specify exactly which points the diagram displays.
Figure 1.
Seven repeating rational-rotation points and the first eight and sixty-four irrational-rotation points
. Labels give the power index ; the points are . The first panel uses , and the other two use . Each finite sample is only an illustration: a finite plot cannot establish that the infinite subgroup is a dense set. Reproduce the diagram with rational-versus-irrational-rotations.py. Details.
This example shows why algebraic generation and closure must be distinguished: one irrational rotation generates a countable cyclic subgroup, yet its closure is the whole uncountable compact group.
Submodular rank function 2026-10-31
On a finite ground set , a submodular rank function is a normalised set function with , a monotone set function, and a submodular set function, such that for . Equivalently, require nonnegative integer values, monotonicity, submodularity and . The diminishing returns characterization of submodularity bounds each marginal by its singleton value. Thus .
These functions are precisely the rank functions of matroids. To see the converse direction, define . It contains the empty set. If , the unit marginal bounds give , so and heredity holds. For augmentation, suppose with . If every had zero marginal over , diminishing returns would keep each marginal zero as they are added successively. This would give , contradicting monotonicity. Some marginal is therefore one, giving an independent augmentation.
Finally any inclusion-maximal in this independence family has for every remaining . Successively adding them and using diminishing returns shows , so the resulting matroid really has rank . The forward direction is submodularity of matroid rank. These integer increment conditions distinguish matroid ranks from arbitrary real-valued submodular functions.
Subnormal number 2026-10-14
A subnormal number is a nonzero representable value smaller in magnitude than the least positive normalized value . Keep the exponent scale fixed at and allow a zero leading digit: the positive values are for integers . This fills the gap toward zero with constant absolute spacing, at the cost of fewer significant digits. Goldberg describes this gradual approach to zero and why it matters for differences of small numbers.[ref]
For binary64 the least positive normalized value is , and subnormal numbers are spaced by . With nearest rounding and gradual underflow enabled, an exact result with has absolute rounding error at most . A uniform relative bound by unit roundoff fails here: rounds to zero under the even-last-digit tie rule, giving relative error one. Machine epsilon measures resolution near one; it does not measure the distance from zero to the first positive value.
Let be a finite set of positive integers and let . Every sum of a subset is an integer in . If , the pigeonhole principle forces two distinct subsets to have equal sums. Thus cannot be a dissociated set.
Cancelling their common intersection even produces two disjoint subsets with the same sum. Positivity means neither remaining subset can be empty. Conversely, equality of two distinct subset sums gives a nonzero relation with coefficients in , exactly the obstruction to being a dissociated set.
For an -element subset of , the largest possible is . Therefore
is a sufficient condition forcing a collision for every such subset. This counting bound is sufficient rather than necessary. Powers of two show how a collision-free collection can instead use the binary representation to make all sums different.
The same stopping rule connects a waiting count to a fixed-length count. Let be the trial number of the th success, and let count successes in the first trials, so has a binomial distribution. For any nonnegative integer ,
The target is still unmet after trials exactly when fewer than successes have occurred. With , and , this gives ; equivalently, , matching . At , the event identity still holds, with and deterministically.
Sudoku Created 2026-10-20 Updated 2026-10-25
A finite constraint satisfaction problem on a array. Each entry must be one of the integers , and every row, column, and designated box must contain each value once. Given entries constrain the possible completions; backtracking searches those completions.
For a finite pattern in a real vector space, pull a finite colouring back to words through the displayed sum map. A combinatorial line with active coordinates J maps to . The Hales-Jewett theorem therefore forces a monochromatic homothetic copy. Integer patterns remain in the integer lattice; choosing b sufficiently large gives the positive-lattice version.
Summation loop verification Created 2026-10-18 Updated 2026-10-31
Compute , the triangular number , for a nonnegative integer . The empty sum gives zero when . Use exact mathematical integers and keep the input unchanged; every comparison and variable assignment is a terminating operation. The original sequential procedure is
require n is an integer and n >= 0
i = 0
s = 0
while i < n:
    i = i + 1
    s = s + i
return s
The order of the two variable assignments matters: the addition uses the newly incremented . For , the pairs at successive condition checks are . At the last check, is false, and the returned sum is .
The precondition is with , under the exact-arithmetic model just stated. The postcondition for returned value is , with still equal to its starting value. At each condition check use the loop invariant
and the loop variant . The equation says that the accumulator is the triangular number for precisely the processed prefix ; the inequalities connect that prefix to the loop's condition.
Figure 1.
The summation loop restores its invariant before each condition check
. Original sequential control flow for the summation loop verification. The blue loop head carries the loop invariant; the orange body increments before adding it to . A false condition leads to the postcondition. The loop variant decreases on the return arrow. All values are mathematical integers and remains unchanged. Details.
Initialization gives , so holds, including when . For preservation, let the old values satisfy and . Write and for the values after both variable assignments. Since are integers, gives , and
Thus the completed body restores . Between the two variable assignments, the equation can be false; the loop invariant is required at the loop head. This preservation step is mathematical induction on the number of completed iterations.
At exit, the false condition gives , while gives . Hence , so : this proves partial correctness. For algorithm termination, gives the nonnegative integer . When the condition is true, ; the terminating body gives . Therefore the loop cannot repeat forever. Together these arguments prove total correctness for every permitted input, including .
Figure 2.
Four additions finish the sum; an unchanged index cannot make progress
. Original exact trace for : five condition checks and four body executions give , while the loop variant decreases from four to zero. The right panel shows the stalled loop from partial correctness: the same program state repeats and never decreases. Its equation remains true, but it never reaches an exit. Details.
Two changes expose what the proof checks. Swapping the two body instructions computes , returning rather than for . Leaving unchanged can preserve an initial equation forever without producing any answer. The first change breaks the intended postcondition; the second breaks algorithm termination. A trace can reveal these failures, while the two proof obligations explain them.
The exact-arithmetic assumption has a concrete boundary. In a stipulated unsigned eight-bit model where each addition wraps modulo , fits in the input representation, but its intended triangular number is . The stored accumulator instead finishes at , so the mathematical postcondition fails. This is integer overflow, and the proof above does not apply to that altered model. Restricting the same implementation to prevents overflow in its stored loop values, since ; alternatively use a representation supporting the required exact integer arithmetic. The equations in the proof are mathematical statements, not instructions to evaluate products in eight bits.
The summatory totient function is . It counts the coprime ordered pairs with . The identity yields for a positive integer .
For an integer with prime factorization , this is the sum of its prime factors with each repeated times. For example, . It differs from the sum of distinct prime factors.