Documentation

CslibFrontier.Foundations.Data.Nat.ResidueSum

Exact counts from streamed residues #

A count N that is known to lie below a modulus m is recovered exactly from residues modulo m: an accumulator that adds one term at a time and reduces modulo m ends at the sum of the terms modulo m (Nat.foldl_range_add_mod), and if the terms are congruent to numbers summing to N < m, it ends at N itself (Nat.foldl_range_add_mod_eq_of_lt). The accumulator is one residue, however many terms are added.

This is how the deterministic counting simulations of #1833 obtain the exact number of accepting choice strings, at most 2 ^ τ, from contractions computed modulo 2 ^ (τ + 1) and summed over all movement schedules.

Main results #

theorem Nat.foldl_range_add_mod (f : ℕ → ℕ) (m a n : ℕ) :
List.foldl (fun (acc i : ℕ) => (acc + f i) % m) (a % m) (List.range n) = (a + ∑ i ∈ Finset.range n, f i) % m

Streaming a sum modulo m. Adding the terms f 0, …, f (n - 1) one at a time to the residue of a and reducing modulo m after each step gives (a + ∑ f i) % m.

theorem Nat.foldl_range_add_mod_eq_of_lt {f g : ℕ → ℕ} {m n N : ℕ} (hfg : ∀ i < n, f i % m = g i % m) (hsum : ∑ i ∈ Finset.range n, g i = N) (hN : N < m) :
List.foldl (fun (acc i : ℕ) => (acc + f i) % m) 0 (List.range n) = N

Exact recovery of a count below the modulus. If each term f i is congruent modulo m to g i, and the g i sum to N < m, the streamed sum of the f i modulo m, from 0, is exactly N.