← LibraryBinary Powering and Exponentiation ChainsEngineering · MathematicsLesson 213/385← PrevNext →
ArticlePublished 7 Aug 20262 min readBy Kevin Joginbinary poweringsquare and multiplymodular exponentiationaddition chains

Multiprecision Arithmetic

Binary Powering and Exponentiation Chains

Square-and-multiply exponentiation, left-to-right and right-to-left variants, windowing, and why exponentiation cost drives primality testing.

Engineering / MathematicsMultiprecision Arithmetic2 min readKV-MATH-0511

Raising an element to a large power appears in almost every algorithm here: pseudoprime tests, discrete logarithms, order computations and the elliptic curve method. Doing it by repeated multiplication is hopeless; binary powering makes it logarithmic.

The basic method

Write the exponent in binary. Squaring the base repeatedly produces the powers of two; multiplying together those corresponding to set bits produces the result.

x^e where e = sum of e_i 2^i, e_i in {0,1}Requires about log2(e) squarings and at most log2(e) multiplications.

Right-to-left binary powering

  1. InitialiseResult is the identity; running value is the base.
  2. Scan bitsFor each bit of the exponent from least significant.
  3. Multiply on set bitIf the bit is set, multiply the result by the running value.
  4. Square alwaysSquare the running value and move to the next bit.

Left-to-right variant

Scanning from the most significant bit instead squares the accumulator and multiplies by the original base when a bit is set. This requires only one working value rather than two, and the multiplier is always the fixed base — which matters when that base is small enough for a cheaper multiplication routine.

Comparing the two scan directions
VariantWorking valuesMultiplierBest when
Right-to-leftTwoVariesExponent arrives least significant first
Left-to-rightOneFixed baseBase is small, or memory is tight

Windowing

Processing several exponent bits at a time reduces the number of multiplications at the cost of precomputing small powers of the base. For a window of w bits, precompute the odd powers up to 2^w, then scan the exponent in windows.

Cost

Cost = O(log e) modular multiplications = O(M(n) log e)n is the bit length of the modulus.

Side channels

Source. Henri Cohen, A Course in Computational Algebraic Number Theory, Springer GTM 138 — 1.2. Structural reference unverified: the source file was not available during authoring; chapter and section numbers are taken from the published edition and have not been checked against a physical copy.

Continue learning

Modular Arithmetic and Montgomery ReductionArticle · MathematicsNEXT LESSON →Integer Square Root and Perfect Power DetectionArticle · MathematicsMultiprecision Division and RemainderArticle · MathematicsThe Euclidean Algorithm: Classical and Binary VariantsArticle · Mathematics