Documentation

CslibFrontier.Foundations.Data.Nat.ConstantDivision

Division by a constant via multiply and shift #

Division by a fixed N can be computed as a multiplication by a precomputed constant followed by dropping low digits: ⌊x / N⌋ = ⌊(m * x) / p ^ (k + e)⌋ for every x < p ^ k, provided p ^ (k + e) ≤ m * N < p ^ (k + e) + p ^ e (Nat.mul_div_pow_eq_div).

Source mapping. Granlund and Montgomery [GM94], §4 (unsigned division), Theorem 4.2, prove the base-2 case for word size W (their N) and divisor d: if 2 ^ (W + ℓ) ≤ m * d ≤ 2 ^ (W + ℓ) + 2 ^ ℓ, then ⌊n / d⌋ = ⌊(m * n) / 2 ^ (W + ℓ)⌋ for 0 ≤ n < 2 ^ W. Nat.mul_div_pow_eq_div generalizes the radix to any positive p, writes k for W and e for ℓ, and uses a strict upper bound, which loses the equality case that Theorem 4.2 allows. This is the form of Li and Liu [LL24], Lemma 5 ("Generalization of [GM94]", §4.2, p. 22 of ePrint 2023/1584), with kI = k and kE = e.

For the multiplier, Li and Liu take kE = ⌈log_p N⌉ and m = ⌈p ^ (kI + kE) / N⌉ (same page); Nat.constDivMultiplier is that choice, and Nat.constDivMultiplier_bounds proves the hypotheses of Nat.mul_div_pow_eq_div for it. The bound m ≤ p ^ (k + 1) in the same lemma is added here: it keeps m * x below p ^ (2k+1) in the ring version CslibFrontier/Crypto/Primitives/Garbling/Arithmetic/ConstantDivision.lean.

Main definitions #

Main results #

References #

theorem Nat.mul_div_pow_eq_div {p N k e m x : ℕ} (hp : 0 < p) (hN : 0 < N) (hlo : p ^ (k + e) ≤ m * N) (hhi : m * N < p ^ (k + e) + p ^ e) (hx : x < p ^ k) :
m * x / p ^ (k + e) = x / N

Multiply and shift: if p ^ (k + e) ≤ m * N < p ^ (k + e) + p ^ e, then for every x < p ^ k the quotient ⌊(m * x) / p ^ (k + e)⌋ is ⌊x / N⌋.

The multiplier ⌈p ^ (k + e) / N⌉ for e = ⌈log_p N⌉.

theorem Nat.constDivMultiplier_bounds {p N : ℕ} (k : ℕ) (hp : 1 < p) (hN : 0 < N) :
p ^ (k + clog p N) ≤ p.constDivMultiplier k N * N ∧ p.constDivMultiplier k N * N < p ^ (k + clog p N) + p ^ clog p N ∧ p.constDivMultiplier k N ≤ p ^ (k + 1)

The multiplier satisfies the bounds of mul_div_pow_eq_div with e = ⌈log_p N⌉, and is at most p ^ (k + 1).