Barrett Reduction
,The primary goal of Barrett reduction is to perform modular reduction efficiently. The standard calculation, x−⌊x/n⌋⋅n, involves a division (x/n), which can be slow. Barrett reduction aims to replace this division.
The Core Idea
Barrett reduction uses multiplications, subtractions, and bit shifts (fast division by powers of 2) instead of a general division. It achieves this using a precomputed value based on the modulus n to approximate the quotient value ⌊x/n⌋.
How it works
Setup and Precomputation
Suppose we are working with integers base b. (Typically b=2 in computers). Consider an integer k such that bk>n. Often, k is chosen such that bk is roughly n2 (e.g., if n fits in w bits, k=2w is common). Now, we precompute the value m:
which acts as a scaled approximation of division by n.
Approximating the Quotient
The true remainder is r=x−q⋅n, where the true quotient is q=⌊x/n⌋. So in Barrett's method we would like to estimate q without dividing x by n.
Consider the product x⋅m. Substituting the definition of m, we get:
Dividing both sides by bk (which is a right shift by k if b=2):
This gives us the approximation to q:
Let's denote this approximation as q^:
How Close is the Approximation?
Notice that we can write bk=⌊bk/n⌋⋅n+r′ for some remainder r′<n. Solving for m, we havem=(bk−r′)/n. Replacing m for the q^ equation, we get:
Comparing q^ to q=⌊x/n⌋, the difference depends on the term (x⋅r′/(n⋅bk)), which is small if bk is large enough relative to x.
For example, if bk>n2, then (x⋅r′/(n⋅bk))<1 which gives us a nice tight bound q−1≤q^ so we need only 1 subtraction at the worst case. If we choose a smaller k such that bk>n, q^ can get as low as q−2, but typically we choose a large bk>n2.
Final Reduction Algorithm
Precomputation (once for fixed n):
Choose k (e.g., k=2⋅bitlength(n)). We assume b=2.
Calculate m=⌊2k/n⌋.
Reduction (for each x):
Calculate q^=⌊(x⋅m)/2k⌋ (intermediate product x⋅m might need k+bitlength(x/n) bits; often only the higher bits are needed since we do a k bit-shift afterwards).
Calculate r^=x−q^⋅n.
Correction: while r^≥n, r^=r^−n
Cost Analysis of Modular Multiplication
Single-Precision case
Suppose the modulus n has bit width of w<word_size. Then, the cost looks like:
Computing x=a⋅b: multiplication of bitwidth w×w→2w .
Computing x⋅m: multiplication of bitwidth 2w×(k−w)→w+k.
Computing q^⋅n: multiplication of bitwidth w×w→2w.
TODO(Batzorig Zorigoo): add multi-precision case
Written by Batzorig Zorigoo of Fractalyze
Last updated