Algorithm Search⌘K

Proofs: Barrett reduction

These are the human proofs of Barrett reduction, at full length.

Barrett reduction returns x mod n after at most two corrections full

This proof shows: correctness.

Claim. Let n≥1n \ge 1 have kk binary digits, so 2k−1≤n<2k2^{k-1} \le n < 2^k, and let μ=⌊4k/n⌋\mu = \lfloor 4^k / n \rfloor (lines L1 and L2). For every integer xx with 0≤x<4k0 \le x < 4^k, let Q=⌊x/n⌋Q = \lfloor x/n \rfloor and R=x−QnR = x - Qn, so 0≤R<n0 \le R < n. Then the estimate qq of line L3 satisfies Q−2≤q≤QQ - 2 \le q \le Q, the loop of line L5 subtracts nn exactly Q−q≤2Q - q \le 2 times, and line L6 returns R=x mod nR = x \bmod n.

Notation. Let a=x/2k−1a = x / 2^{k-1} and b=4k/nb = 4^k / n, two non-negative rationals, and let x1=⌊a⌋x_1 = \lfloor a \rfloor, so that line L3 computes q=⌊x1μ/2k+1⌋q = \lfloor x_1 \mu / 2^{k+1} \rfloor with μ=⌊b⌋\mu = \lfloor b \rfloor. Then

ab2k+1=x⋅4k2k−1⋅n⋅2k+1=xn.\frac{ab}{2^{k+1}} = \frac{x \cdot 4^k}{2^{k-1} \cdot n \cdot 2^{k+1}} = \frac{x}{n}.

Bounds on the factors. Since x<4kx < 4^k, a<22k/2k−1=2k+1a < 2^{2k}/2^{k-1} = 2^{k+1}. Since n≥2k−1n \ge 2^{k-1}, μ≤b≤22k/2k−1=2k+1\mu \le b \le 2^{2k}/2^{k-1} = 2^{k+1}. Also 0≤a−x1<10 \le a - x_1 < 1 and 0≤b−μ<10 \le b - \mu < 1.

Upper bound. x1≤ax_1 \le a and μ≤b\mu \le b, with all four numbers non-negative, so x1μ≤abx_1 \mu \le ab and x1μ/2k+1≤x/nx_1\mu / 2^{k+1} \le x/n. Taking floors, q≤⌊x/n⌋=Qq \le \lfloor x/n \rfloor = Q.

Lower bound. Write

ab−x1μ=a(b−μ)+μ(a−x1).ab - x_1 \mu = a(b - \mu) + \mu(a - x_1).

The first term is at most a<2k+1a < 2^{k+1}, because 0≤b−μ<10 \le b - \mu < 1 and a≥0a \ge 0. The second term is less than μ≤2k+1\mu \le 2^{k+1} when μ>0\mu > 0, because 0≤a−x1<10 \le a - x_1 < 1, and it is 00 when μ=0\mu = 0. If x=0x = 0, then q=0=Qq = 0 = Q and there is nothing to prove; otherwise a>0a > 0 and the first term is less than aa. In all cases ab−x1μ<2k+1+2k+1=2k+2ab - x_1\mu < 2^{k+1} + 2^{k+1} = 2^{k+2}. Dividing by 2k+12^{k+1},

x1μ2k+1>xn−2≥Q−2.\frac{x_1 \mu}{2^{k+1}} > \frac{x}{n} - 2 \ge Q - 2.

The integer Q−2Q - 2 is strictly less than x1μ/2k+1x_1\mu / 2^{k+1}, so it is at most the floor of this number: Q−2≤qQ - 2 \le q.

The corrections. Line L4 sets r=x−qn=(Q−q)n+Rr = x - qn = (Q - q)n + R. By the two bounds, Q−q∈{0,1,2}Q - q \in \{0, 1, 2\}, so 0≤r<3n0 \le r < 3n and r≡x(modn)r \equiv x \pmod n. Each pass of the loop in line L5 keeps r≡x(modn)r \equiv x \pmod n and lowers rr by nn; the loop stops at the first value below nn. Starting from (Q−q)n+R(Q - q)n + R with 0≤R<n0 \le R < n, it makes exactly Q−q≤2Q - q \le 2 passes and ends with r=Rr = R. Line L6 returns R=x mod nR = x \bmod n.

Products of residues. For 0≤a′,b′<n0 \le a', b' < n, the product satisfies a′b′≤(n−1)2<4ka'b' \le (n - 1)^2 < 4^k, so line L7 is within the range of the claim and returns a′b′ mod na'b' \bmod n. ■\blacksquare

Back to Barrett reduction