← LibraryMultiprecision Integer ArithmeticEngineering · MathematicsLesson 22/32← PrevNext →
ArticlePublished 6 Aug 2026Updated 5 Aug 20268 min readBy Kevin Jogin
KEVOS® Knowledge Library · Engineering → Mathematics

Engineering/Mathematics/Algorithm engineering

Multiprecision Integer Arithmetic

Every algorithm in this library is ultimately a sequence of big-integer operations, and modular exponentiation dominates almost all of them. Improving the inner multiply-and-reduce loop by a constant factor improves an entire cryptographic system by that same factor.

  • Implementation core
  • Computing
  • Performance critical
  • ≈17 min read
  • Underpins every other algorithm
O(ℓ²)SchoolbookClassical multiplication of -bit integers; still the fastest choice below a few hundred bits.
O(ℓ^1.585)KaratsubaThree half-size multiplications instead of four; the standard crossover is a few hundred bits.
1.5ℓSquare-and-multiplyExpected modular multiplications for an -bit exponent, reducible to about 1.2ℓ with windowing.
0 divisionsMontgomeryReplaces trial division in modular reduction with shifts and multiplications — the reason it dominates in practice.

01

Executive summary

A multiprecision integer is an array of machine words in base 2w, with a separate sign. Addition and subtraction are linear and uninteresting; multiplication, division and modular reduction are where all the engineering lies.

Three decisions determine performance. Which multiplication algorithm applies at the operand size in question. How modular reduction is performed — trial division, Barrett, or Montgomery. And how exponentiation is sequenced, since the exponentiation loop determines how many multiplications and reductions occur at all. For cryptographic code a fourth constraint applies throughout: the execution path must not depend on secret data.

Relative cost of one 2048-bit modular multiplication by reduction strategy (schematic)
Multiply then trial division1.00×
Multiply then Barrett reduction0.62×
Montgomery multiplication0.55×
Montgomery, interleaved and unrolled0.45×
Contents

02

Representation

  • Base. Store digits in base 2w where w is 32 or 64. A full-width base requires access to the high half of a word product — available as a widening multiply on most architectures. Some libraries use a reduced radix such as 251 or 226 to allow lazy carry propagation and to exploit floating-point or vector units.
  • Sign. Sign–magnitude is standard for arbitrary-precision integers, because two's complement has no natural fixed width. Comparison then reduces to a length check followed by a digit-wise scan from the most significant end.
  • Normalisation. Maintain the invariant that the top digit is non-zero, so that length equals significance. Failing to normalise after a subtraction is a classic source of subtle bugs in comparison and division routines.
  • Length and size. The bit length is ℓ = (d−1)w + ⌈log2(top digit + 1)⌉ for d digits. Every complexity bound in this library is expressed in terms of this quantity.
Contents

03

Multiplication

Multiplication algorithms and where they apply
AlgorithmComplexityIdeaPractical range
SchoolbookO(ℓ2)Digit-by-digit with carry accumulationUp to a few hundred bits; best constants
KaratsubaO(ℓ1.585)Three half-size products via (a0+a1)(b0+b1)Roughly 300–10,000 bits
Toom–Cook (Toom-3)O(ℓ1.465)Evaluate, multiply pointwise, interpolateThousands of bits
Schönhage–StrassenO(ℓ log ℓ log log ℓ)FFT over a ring of the form ℤ/(2k+1)Tens of thousands of bits and up
Harvey–van der HoevenO(ℓ log ℓ)Multidimensional FFT constructionTheoretical; galactic crossover

Squaring is a special case worth implementing separately: half the digit products are duplicated, giving roughly a 30–40% saving over a general multiply.

Theorem T1

The Karatsuba identity

(a1B + a0)(b1B + b0) = a1b1B2 + [(a1+a0)(b1+b0) − a1b1 − a0b0]B + a0b0Three half-size multiplications plus additions, giving the recurrence T(ℓ) = 3T(ℓ/2) + O(ℓ) and hence ℓ^{log₂3}.

Division is the expensive primitive

Classical division with remainder is O(ℓ2) like multiplication, but with much worse constants: each step requires a quotient-digit estimate and a correction. This asymmetry is the entire motivation for Montgomery and Barrett reduction, both of which replace division by multiplication and shifting.

Contents

04

Modular reduction

01

Trial division

Compute a mod n directly by long division. Correct, simple, and the slowest option. Acceptable when reductions are rare relative to other work.

02

Barrett reduction

Precompute μ = ⌊B2k/n⌋ once, then estimate the quotient with two multiplications and correct by at most two subtractions. Best when inputs are arbitrary and the modulus is reused.

03

Montgomery reduction

Work with residues scaled by R = 2wk. Reduction becomes multiply, add, shift — no division at all. Best when many operations share one modulus, as in exponentiation.

04

Special-form moduli

Pseudo-Mersenne primes such as 2255−19 reduce by a shift and a multiply-by-small-constant. This is why modern curve parameters are chosen with that shape.

Montgomery multiplication of a, b < n (n odd, R = 2^{wk} > n)

  1. precompute n′ = −n^{-1} mod 2^w (one extended gcd, done once per modulus)
  2. T ← a·b // Montgomery-domain operands
  3. for i = 0 .. k−1:
  4. m ← (T mod 2^w)·n′ mod 2^w
  5. T ← (T + m·n·2^{wi}) / 2^w // exact division: the low word is zero by construction
  6. if T ≥ n: T ← T − n
  7. return T // equals a·b·R^{-1} mod n

2k² + O(k) word multiplications for a k-word modulus — the same order as one schoolbook multiplication, with no division. Conversion into and out of the Montgomery domain costs one extra multiplication each way, amortised over the whole exponentiation.

The final conditional subtraction is a side channel

The last step of Montgomery reduction executes only sometimes, and whether it executes depends on the operands. In secret-key code this must be made unconditional — for example by always performing the subtraction into a scratch buffer and selecting the result with a constant-time mask. The same discipline applies to every branch and every table index in the exponentiation loop.

Contents

05

Modular exponentiation

Exponentiation is the dominant cost in RSA, Diffie–Hellman and primality testing, so its structure matters more than any other single choice.

Exponentiation strategies for an ℓ-bit exponent
MethodMultiplicationsMemoryNotes
Left-to-right binary squarings + ℓ/2 multiplications on averageO(1)Simplest; the baseline
Fixed window, width k squarings + ℓ/k multiplications2k precomputed valuesWindow 4–6 is typical at 2048 bits
Sliding window squarings + about ℓ/(k+1) multiplications2k−1 valuesBetter than fixed window; variable pattern leaks unless equalised
Montgomery ladder squarings + multiplicationsO(1)Uniform operation sequence; the standard constant-time choice
CRT exponentiation (RSA)two half-size exponentiationstwo moduliAbout a fourfold speed-up for private operations

Counts are modular multiplications; each costs O(ℓ²) bit operations classically, giving the familiar O(ℓ³) total.

  • Combine CRT with windowing. The RSA private operation should use CRT to halve the operand size and windowing within each half; the two optimisations multiply.
  • Guard the CRT recombination. A fault during one of the two half-exponentiations lets an attacker recover the factorization from a single incorrect signature. Verify the signature before releasing it, or recompute and compare.
  • Blind the exponent and the base when the exponent is secret: replace d by d + r·λ(n) and the base by rex, then correct at the end. This defeats timing and simple power analysis that target the exponent bits.
  • Never branch on secret data — including table indices, which leak through cache timing. Scatter–gather or full-table scanning is required for window methods on secret exponents.
Contents

06

Engineering checklist

What to verify in a multiprecision layer
AreaCheckFailure mode if skipped
Carry handlingExhaustive tests at word boundaries and all-ones patternsRare, data-dependent wrong answers
NormalisationTop digit non-zero after every operationComparison and division errors
Negative operandsSign handling in subtraction, division and modular reductionWrong sign of remainder; silent corruption
Zero and oneDegenerate inputs to every routineCrashes or infinite loops in division
Modulus parityMontgomery requires an odd modulusSilent incorrect results
Constant timeNo secret-dependent branches, indices or loop countsTiming and cache side channels
Memory hygieneZeroing intermediate buffersKey material recoverable from freed memory
Cross-validationDifferential testing against a reference libraryUndetected algorithmic errors

A note on building versus adopting

Mature libraries — GMP for general work, and hardened cryptographic libraries for key operations — encode decades of correctness and side-channel experience. Writing a multiprecision layer is an excellent way to understand the algorithms and a poor way to obtain production cryptography. Where a custom implementation is unavoidable, differential testing against a reference implementation across millions of random inputs is the minimum acceptable validation.

Contents

07

Quick reference and FAQ

Costs on ℓ-bit operands
OperationClassicalWith fast multiplication
Add, subtractO(ℓ)O(ℓ)
MultiplyO(ℓ2)Õ(ℓ)
SquareO(ℓ2), ≈0.6× multiplyÕ(ℓ)
Divide with remainderO(ℓ2)Õ(ℓ)
Modular multiply (Montgomery)O(ℓ2)Õ(ℓ)
Modular exponentiationO(ℓ3)Õ(ℓ2)
gcdO(ℓ2)Õ(ℓ)
Base conversionO(ℓ2)Õ(ℓ)
At what size does Karatsuba actually beat schoolbook?
Typically between 300 and 600 bits on modern 64-bit hardware, depending on how well the schoolbook inner loop is tuned. Well-optimised assembly for the classical algorithm pushes the crossover higher, which is why library thresholds are tuned per platform rather than fixed.
Why is Montgomery multiplication preferred over Barrett for exponentiation?
Because the whole computation stays in the Montgomery domain: conversion happens once at the start and once at the end, and every intermediate multiplication avoids division. For a single isolated reduction Barrett is often simpler and equally good.
Does Montgomery work with an even modulus?
No — it requires gcd(n, R) = 1 with R a power of two, so n must be odd. Even moduli are handled by splitting off the power of two and using CRT, or by using Barrett reduction instead.
How much does the CRT optimisation really save in RSA?
Close to a factor of four. Two exponentiations at half the modulus size cost about 2 × (1/2)3 = 1/4 of the full-size operation under a cubic cost model, and measurements agree closely with that estimate.
Contents

09

References and further reading

  • V. Shoup, A Computational Introduction to Number Theory and Algebra, Cambridge University Press, 2005 — Chapter 3.
  • D. E. Knuth, The Art of Computer Programming, Vol. 2, 3rd ed., Addison-Wesley, 1997 — §4.3, the classical reference on multiprecision arithmetic.
  • P. L. Montgomery, 'Modular multiplication without trial division', Math. Comp. 44 (1985) 519–521.
  • R. P. Brent and P. Zimmermann, Modern Computer Arithmetic, Cambridge, 2010.
  • P. C. Kocher, 'Timing attacks on implementations of Diffie–Hellman, RSA, DSS, and other systems', CRYPTO '96, LNCS 1109, 104–113.

KEVOS® Knowledge LibraryEngineering → MathematicsTaxonomy ID: ENG-MATHPage ID: multiprecision-integer-arithmeticReview cycle: annual


Continue learning

Asymptotic Notation and Machine ModelsArticle · MathematicsNEXT LESSON →Euclid's Algorithm and Modular ComputationArticle · MathematicsLinearly Generated Sequences and Sparse Linear SystemsArticle · MathematicsProbabilistic AlgorithmsArticle · Mathematics