If we want to compute many instances of ab mod n for a fixed modulus n (where 0≤ab<n^2), we can avoid the slowness of long division and instead perform these modular reductionsusing the Barrett reduction algorithm. For the given n we precompute a factor using division;thereafter the computations of ab mod n
only involve multiplications, subtractions, and shifts (all of which are fasteroperations than division).
Algorithm
Precomputation:
Reduction:
Proof of correctness
Bit widthanalysis
Comparison withMontgomery reduction
The Barrettalgorithm and Montgomery reduction algorithm can bothspeed up modular reductions.
Similarities:
Differences:
Montgomeryreduction requires numbers to be converted into and out of “Montgomery form”(expensive operations that require a true modulo operation in each direction),whereas Barrett reduction operates on regular numbers directly. This makesMontgomery reduction suitable for modular exponentiation but not for workingwith various unrelated numbers.
Montgomery isbased on modular congruences and exact division, whereas Barrett is based onapproximating the real reciprocal with bounded precision.
If the modulusis k bits long,then Montgomery internally performs two k-by-k bitmultiplications yielding 2k bits. ButBarrett internally performs a 2k-by-k bit multiplication yielding 3k bits, plus a k-by-k bit multiplication yielding 2k bits, so the Barrett algorithm is more expensive. (The bit lengthsstated in this paragraph are slightly inexact, to within O(1).)
Source code SHAPE \* MERGEFORMAT
My Javaimplementation of Barrett reduction for int/long and BigInteger, withself-check and speed benchmark:
SmallBarrettReducer.java (modulus <2^21, self-check and benchmark)
BigBarrettReducer.java (BigInteger modulus, self-check only)
On x86processors it appears that the native int64 modulo is as fast as Barrettreduction. The benchmark in SmallBarrettReducer shows both techniques beingabout the same speed. But on a CPU without a hardware divider, you might seeBarrett reduction be measurably faster. For BigBarrettReducer, no benchmark isprovided because the method BigInteger.modulo() isimplemented quite fast.
A Pythonimplementation with the full core algorithm but a less elaborate self-check isalso available:
A shortMathematica program demonstrates the full computation, but doesn’t implementcaching or data structures:
Categories: Programming, Math, Java, Python
Last updated: 2019-07-29
1317




被折叠的 条评论
为什么被折叠?



