7. Arbitrary Precision

When 64 bits aren't enough

Every RSA encryption key you've ever used was generated by multiplying two integers hundreds of digits long. Every modern TLS handshake depends on arithmetic over numbers that don't fit in any CPU register. Scientific simulations of physical constants demand fifty or a hundred significant decimal digits. Mathematical proof assistants must verify results exactly, with zero rounding error.

Standard 64-bit floating-point gives you about fifteen significant decimal digits. Standard 64-bit integers give you values up to about 9.2 × 10¹⁸. For most programs, that's plenty. For cryptography, verified numerics, and exact symbolic mathematics, it's nowhere near enough.

Arbitrary-precision arithmetic solves this by representing numbers as data structures of configurable size — spending as much memory and compute as needed to achieve the required precision.

Why We Need It

The needs arise in a handful of very different domains, each pushing against 64-bit limits in its own way.

Cryptography. RSA key generation requires choosing two large primes, typically 1024 bits each, and multiplying them to form a 2048-bit modulus. Every encryption and decryption operation involves modular exponentiation on numbers of that size. Elliptic curve cryptography works over finite fields with 256- to 521-bit primes. None of this is possible with machine-word arithmetic.

Scientific computing. Physical constants such as π or the fine-structure constant are sometimes needed to hundreds of digits — for instance, to verify numerical results against known identities, or to run simulations where cancellation errors would destroy double-precision accuracy. The MPFR library lets you set precision to thousands of bits, paying with time and memory but gaining guaranteed accuracy.

Financial computation. Some financial systems use arbitrary-precision decimal arithmetic to ensure that currency amounts round exactly, avoiding the famous pitfall where 0.1 + 0.2 ≠ 0.3 in binary floating point.

Mathematical proofs. Automated theorem provers and computer algebra systems must work with exact rational numbers, algebraic numbers, or symbolic integers without ever introducing rounding error. If a proof system rounds intermediate results, it cannot make absolute guarantees.

The Core Tradeoff

Hardware arithmetic is fast because the operand size is fixed — the ALU is a fixed-width circuit. Arbitrary precision trades that speed for unbounded range, using software loops to process numbers one machine word at a time.

Bigint Representation

A big integer is stored as an array of ordinary integers called limbs. Each limb holds a fixed number of bits — typically 32 or 64. The limbs together represent the full magnitude of the number in a chosen base (2³² or 2⁶⁴).

Most implementations use little-endian limb order: limb 0 holds the least significant bits, limb 1 the next chunk, and so on. This mirrors the way little-endian machines store bytes, and makes it easy to extend the array when arithmetic produces a carry out of the most significant limb.

Diagram

192-bit Bigint: Three 64-bit Limbs

A 192-bit bigint: three 64-bit limbs (little-endian) limbs[0] limbs[1] limbs[2] bits 0–63 bits 64–127 bits 128–191 least significant most significant carry carry value = limbs[0] + limbs[1] × 2⁶⁴ + limbs[2] × 2¹²⁸ (treating each limb as an unsigned 64-bit integer)
A 192-bit bigint stored as three 64-bit limbs in little-endian order. Limb 0 holds the least significant 64 bits. Carries propagate left during arithmetic.

The sign is stored separately — typically as a single boolean or as a sign-magnitude convention. The limb array always represents the absolute value; operations combine the limbs and the sign flag independently.

A crucial detail: the array length is variable. If you add two 192-bit numbers and get a 193-bit result, the implementation appends a new limb (containing just the carry bit) rather than overflowing.

Bigint Arithmetic

Addition

Bigint addition is the grade-school column algorithm applied to limbs instead of decimal digits.

Adding two 128-bit numbers (two limbs each)

a = [a0, a1]   (a0 = low 64 bits, a1 = high 64 bits)
b = [b0, b1]

Step 1: result[0] = a0 + b0 carry = (a0 + b0) >> 64 // 1 if sum overflowed 64 bits

Step 2: result[1] = a1 + b1 + carry carry = (a1 + b1 + carry) >> 64

If carry remains after all limbs: result[2] = carry // extend the array by one limb

The time complexity is O(n) where n is the number of limbs. Each limb requires one 64-bit addition and one carry check — in practice a handful of CPU instructions.

Subtraction

Subtraction is the mirror image of addition: instead of a carry rippling out of the top of a limb, a borrow ripples in from the limb above. When the digit you're subtracting is larger than the digit you have, you borrow one unit of the base (2⁶⁴) from the next-higher limb, exactly as you borrowed from the next column in grade-school subtraction.

But there's a wrinkle that addition doesn't have. Because the article's bigints are sign-magnitude — the limb array always holds the absolute value and the sign lives in a separate flag — the limb-subtraction routine can only handle the case where the number being subtracted is no larger than the number it's taken from. If it were larger, the result would go negative and the borrow would fall off the top with nowhere to go.

So subtraction begins with a magnitude compare. To compute A − B on the absolute values:

  1. If |A| ≥ |B|, subtract limb-by-limb as B from A and give the result A's sign.
  2. If |A| < |B|, subtract A from B instead — so the smaller magnitude is always the one being taken away — and flip the sign of the result.

Comparing two magnitudes is cheap. First compare limb counts (after stripping leading zeros, more limbs means a larger magnitude). If the counts match, walk from the most significant limb downward and return at the first pair that differs. Only if every limb is equal are the magnitudes equal.

Diagram

Borrow Propagation: 2⁶⁴ − 1

A = [0, 1] minus B = [1, 0] (little-endian, base 2⁶⁴) limbs[0] limbs[1] 0 − 1 1 − 0 − 1 → 0xFFFF…FFFF → 0 borrow 1 limb 0 underflows → borrow from limb 1 → result [0xFFFF…FFFF, 0] strip the leading zero limb → [0xFFFFFFFFFFFFFFFF] = 2⁶⁴ − 1
Subtracting B = 1 from A = 2⁶⁴. Limb 0 (0 − 1) underflows, so it borrows one unit of the base from limb 1. The borrow leaves limb 1 at zero, which is then stripped during normalization.

Subtracting with a borrow: 2⁶⁴ − 1

a = [0, 1]     (a0 = 0, a1 = 1)   →  value 2⁶⁴
b = [1, 0]     (b0 = 1, b1 = 0)   →  value 1

Compare |a| vs |b|: a has a nonzero high limb, so |a| ≥ |b|. OK.

Step 1: a0 − b0 = 0 − 1 underflows (0 < 1) result[0] = 0 − 1 + 2⁶⁴ = 0xFFFFFFFFFFFFFFFF borrow = 1

Step 2: a1 − b1 − borrow = 1 − 0 − 1 = 0 result[1] = 0 borrow = 0

Normalize: strip the leading zero limb (result[1] = 0) result = [0xFFFFFFFFFFFFFFFF] = 2⁶⁴ − 1

Like addition, subtraction is O(n): one pass over the limbs, each doing a single 64-bit subtract-with-borrow. The extra magnitude compare is also O(n) and usually returns after inspecting only the top limb. Normalization — stripping leading zero limbs so the length reflects the true magnitude — matters here because subtraction is the one basic operation that can make a number shorter, and later operations rely on the limb count being exact.

Multiplication

Schoolbook multiplication is the direct translation of the grade-school algorithm. To multiply an m-limb number by an n-limb number, compute every pairwise product of limbs and sum them into the right position of the result array.

Schoolbook: multiplying limb arrays A[m] × B[n]

result = array of (m + n) limbs, zeroed

for i from 0 to m-1: carry = 0 for j from 0 to n-1: product = A[i] * B[j] + result[i+j] + carry result[i+j] = product & LIMB_MASK // low 64 bits carry = product >> 64 // high 64 bits result[i+n] += carry

Each inner step requires a 64×64→128-bit multiply. Modern CPUs provide a mulq or mul instruction that produces a 128-bit result in two registers.

Schoolbook is O(n²). For numbers with n limbs, it's fast enough up to a few hundred limbs — but for RSA-scale work (thousands of bits), better algorithms are needed.

Karatsuba multiplication exploits a clever algebraic identity to reduce four sub-multiplications to three.

Given two n-limb numbers A and B, split each into two halves:

Karatsuba split

A = A_hi × B_size + A_lo    (split at midpoint)
B = B_hi × B_size + B_lo

A × B = A_hi×B_hi × B_size² + (A_hi×B_lo + A_lo×B_hi) × B_size + A_lo×B_lo

Naively this needs four multiplications: A_hi×B_hi, A_hi×B_lo, A_lo×B_hi, A_lo×B_lo. Karatsuba computes just three.

Diagram

Schoolbook vs. Karatsuba Multiplication

Schoolbook: 4 multiplications Karatsuba: 3 multiplications A_hi × B_hi A_hi × B_lo A_lo × B_hi A_lo × B_lo 4 multiplications → O(n²) z2 = A_hi×B_hi z0 = A_lo×B_lo z1 = (A_hi+A_lo) ×(B_hi+B_lo) − z2 − z0 3 multiplications → O(n^1.585)
Schoolbook requires four sub-multiplications (quadrants of the product grid). Karatsuba computes z2 = A_hi×B_hi and z0 = A_lo×B_lo directly, then derives the cross-term z1 from a single extra multiplication — saving one recursive call.

The identity that makes Karatsuba work:

Karatsuba identity

z2 = A_hi × B_hi
z0 = A_lo × B_lo
z1 = (A_hi + A_lo) × (B_hi + B_lo) − z2 − z0

A × B = z2 × BASE² + z1 × BASE + z0

Three multiplications of half-size numbers instead of four. Applied recursively, this gives O(n^log₂3) ≈ O(n^1.585).

Toom-Cook generalizes this: split each operand into k pieces and reduce k² sub-multiplications to 2k−1. Toom-3 (three pieces) gives O(n^log₃5) ≈ O(n^1.465). For extremely large numbers — millions of bits — the Schönhage-Strassen algorithm and the newer Harvey-Hoeven algorithm use number-theoretic transforms to achieve near-linear multiplication, but these are complex to implement and only win at immense sizes.

In practice, implementations use schoolbook for small inputs, switch to Karatsuba at a threshold (typically 20–80 limbs), and then Toom-Cook or FFT-based methods for very large numbers.

Division

Division is the hard one. Addition, subtraction, and multiplication all have a pleasant property: each output digit can be computed from the input digits by a fixed local formula, so the whole thing is one or two clean passes over the limbs. Division has no such formula. Each quotient digit depends on the running remainder left behind by the digits above it, so you cannot compute them in parallel — you have to grind them out one at a time, top down, threading the remainder through the whole process.

The workhorse algorithm is grade-school long division, generalized from base 10 to a large base like 2⁶⁴. This is Knuth's Algorithm D (from The Art of Computer Programming, Vol. 2). The difficulty it has to solve is that, in base 10, you guess each quotient digit by eye ("how many times does 47 go into 380? about 8") and the guess is easy because there are only ten choices. In base 2⁶⁴ there are 2⁶⁴ choices, so you need a way to estimate each quotient limb arithmetically and then correct the estimate.

Normalize first. Before dividing, scale both the dividend and the divisor by the same factor so that the divisor's most significant limb has its high bit set (its top limb is ≥ half the base). Scaling both operands by the same amount leaves the quotient unchanged and only scales the final remainder, which you undo at the end. Normalization is what makes the digit estimate reliably close to the truth.

Estimate each quotient limb. With a normalized divisor, estimate the next quotient limb from just the top two limbs of the running remainder divided by the top limb of the divisor:

q^=min⁡ ⁣(⌊rtop⋅B+rnextdtop⌋,  B−1)\hat{q} = \min\!\left(\left\lfloor \frac{r_{\text{top}} \cdot B + r_{\text{next}}}{d_{\text{top}}} \right\rfloor,\; B - 1\right)

where B=264B = 2^{64} is the base. Thanks to normalization, this estimate q^\hat{q} is never too low, and too high by at most 2 — a remarkable guarantee, given that it ignores every limb below the top two. An extra test against the divisor's second limb tightens the overshoot to at most 1, so at most a single correction is ever needed in practice.

Multiply back and correct. Compute q^×d\hat{q} \times d and subtract it from the running remainder. If the subtraction goes negative, the estimate was too high: decrement q^\hat{q} by one, add the divisor back once, and — in the rare double-overshoot case — repeat. When the remainder is non-negative and smaller than the divisor, that quotient limb is final; shift in the next limb of the dividend and repeat for the limb below.

Diagram

One Quotient Limb: Estimate → Multiply → Subtract → Correct

The inner loop that produces one quotient limb 1. Estimate q̂ = ⌊(r_top·B + r_next)/d_top⌋ 2. Multiply t = q̂ × d 3. Subtract r = r − t 4. Correct if r < 0: q̂−−, r += d rare double overshoot → correct again (at most twice)
Each quotient limb is guessed from the top of the remainder, checked by multiplying the whole divisor back, then subtracted. If the remainder goes negative the estimate was one too high, so the quotient limb is decremented and the divisor added back — at most twice.

The example below runs the whole loop by hand in base 10, where the estimate-and-correct step is visible to the naked eye. Real implementations do exactly this in base 2³² or 2⁶⁴; only the base changes.

Long division with a correction: 8007 ÷ 89 (base 10)

Divisor d = 89. Its top digit is 8 ≥ 5 (half the base),
so d is already normalized — no scaling needed.

--- Quotient digit 1 --------------------------------- Running remainder starts as the top digits: 800 Estimate: top two digits 80, top digit of d is 8 q̂ = min(⌊80 / 8⌋, 9) = min(10, 9) = 9 Multiply back: 9 × 89 = 801 Subtract: 800 − 801 = −1 → NEGATIVE, overshoot! Correct: q̂ = 8, 8 × 89 = 712 800 − 712 = 88 → remainder 88, digit = 8

--- Quotient digit 2 --------------------------------- Bring down next dividend digit 7 → remainder 887 Estimate: top two digits 88, top digit of d is 8 q̂ = min(⌊88 / 8⌋, 9) = min(11, 9) = 9 Multiply back: 9 × 89 = 801 Subtract: 887 − 801 = 86 → non-negative, no correction remainder 86, digit = 9

Result: quotient = 89, remainder = 86 Check: 89 × 89 + 86 = 7921 + 86 = 8007 ✓

Schoolbook long division costs O(n·m): one quotient limb for each of the n limbs of the quotient, and each limb requires a multiply-back of the m-limb divisor. For a balanced 2n ÷ n division that's O(n²), the same asymptotic class as schoolbook multiplication.

And, as with multiplication, you can do better. Fast division reduces to multiplication. The Newton–Raphson approach computes a high-precision reciprocal of the divisor by iterating xk+1=xk(2−d xk)x_{k+1} = x_k(2 - d\,x_k) — each iteration doubles the number of correct bits and costs one multiplication — and then multiplies the dividend by that reciprocal. Divide-and-conquer schemes (Burnikel–Ziegler) split the problem recursively the same way Karatsuba does. Either way, division inherits the speed of whatever multiplication algorithm sits underneath it, so on very large numbers it runs in the same sub-quadratic (ultimately near-linear) time as the multiply it's built on.

Bigfloat

A big float (arbitrary-precision floating-point number) extends IEEE 754 by replacing the fixed-width mantissa with an array of limbs at user-specified precision.

Bigfloat structure

struct BigFloat {
  sign:      +1 or −1
  mantissa:  BigInt of user-specified precision (e.g. 256 bits)
  exponent:  ordinary signed integer (base 2)
  precision: number of bits in the mantissa
}

value = sign × mantissa × 2^exponent

The mantissa is normalized so its most significant bit is 1, exactly as in IEEE 754, but it can be thousands of bits wide.

Operations on bigfloats work exactly like IEEE 754 — but after each operation, the result is rounded to the configured precision. The rounding mode is configurable: round-nearest, round-up, round-down, or round-toward-zero. This last point is crucial for the interval arithmetic we'll see in the next article.

How GMP and MPFR Work

GMP (GNU Multiple Precision Arithmetic Library) is the reference implementation for arbitrary-precision integers and rationals. It is written in C with hand-tuned assembly for critical inner loops (especially the multiply inner loop, which uses platform-specific SIMD and multi-word multiply instructions). GMP automatically selects the best algorithm for the operand sizes at runtime.

MPFR (Multiple Precision Floating-Point Reliable library) builds on GMP to provide correctly-rounded arbitrary-precision floating point. Its defining feature is that every operation is correctly rounded: for any precision setting and any rounding mode, the result is as if you computed the exact mathematical result and then rounded it once. This property — called correct rounding — means MPFR results are reproducible and auditable across platforms.

Using MPFR in C (conceptual)

mpfr_t x, y, result;
mpfr_init2(x,      256);   // 256-bit precision
mpfr_init2(y,      256);
mpfr_init2(result, 256);

mpfr_set_d(x, 2.0, MPFR_RNDN); mpfr_sqrt(result, x, MPFR_RNDN); // √2 to 256 bits, correctly rounded

// result now holds √2 to ~77 significant decimal digits

Both libraries are used as backends by computer algebra systems (Sage, Mathematica internals), arbitrary-precision calculators (bc), and scientific programming environments (Python's mpmath, Julia's BigFloat).

JavaScript BigInt

Since ES2020, JavaScript has a native BigInt type. You write it with an n suffix or use the BigInt() constructor:

JavaScript BigInt basics

const a = 12345678901234567890n;
const b = BigInt("98765432109876543210");

console.log(a + b); // 111111111011111111100n console.log(a * b); // very large integer, exact console.log(2n ** 256n); // 2²⁵⁶, exact

// RSA-scale integer const p = 179769313486231570815n; // truncated for display

JavaScript BigInt is integer-only — there is no BigFloat in the language standard (as of 2026, though the Decimal proposal is advancing). Key limitations:

  • No fractional part. Division truncates toward zero. 7n / 2n === 3n.
  • No interop with Number without explicit conversion. You cannot add a BigInt and a Number directly — 1n + 1 throws a TypeError.
  • No bitwise float operations. You can't manipulate the IEEE 754 bit pattern of a BigFloat because BigFloat doesn't exist yet.
  • Performance. V8 and SpiderMonkey implement Karatsuba for large BigInts, but for multi-kilobit arithmetic (like RSA), JavaScript is significantly slower than GMP. Cryptographic libraries in JavaScript (like noble-curves) work around this with highly optimized BigInt arithmetic tuned to specific field sizes.

BigInt vs. Number in JavaScript

Number.MAX_SAFE_INTEGER is 2⁵³ − 1 = 9,007,199,254,740,991. Any integer larger than this cannot be represented exactly as a IEEE 754 double — consecutive values may be indistinguishable. BigInt has no such limit; every integer is exact, however large.

Key Takeaways

  • Arbitrary-precision arithmetic stores numbers as arrays of machine-word "limbs" of configurable length
  • Addition and subtraction are O(n); schoolbook multiplication is O(n²); Karatsuba is O(n^1.585)
  • Bigfloats extend the mantissa to any width; the precision and rounding mode are user-configurable
  • GMP handles integers; MPFR adds correctly-rounded floating-point on top
  • JavaScript's native BigInt covers arbitrary integers but not arbitrary-precision floats
  • The performance cost over fixed-width arithmetic is real — these libraries are used only where exact or very-high-precision results are required

Try It Yourself — Bigint Addition

Enter two integers below. They are split into 16-bit limbs (0x0000–0xFFFF) and added limb-by-limb with carry propagation — exactly how GMP and other bigint libraries work internally. Step through the process or view all steps at once.

Try It Yourself — Schoolbook vs Karatsuba

Enter two integers and see how many base-case multiplications each algorithm requires. The recursion tree shows how Karatsuba splits each problem into three sub-multiplications (z0, z1, z2) instead of four. Try larger numbers to see the savings grow.

Try It Yourself — Long Division Stepper

Enter a dividend and a divisor. The stepper runs grade-school long division the way Algorithm D does: for each quotient digit it shows the estimate from the top of the running remainder, multiplies the whole divisor back, subtracts it, and — when the estimate was one too high — shows the correction that decrements the digit and adds the divisor back. Step through digit by digit or run it all at once.

Arbitrary precision eliminates rounding error by making numbers as wide as needed — but it can't tell you how wrong a result might be when the inputs themselves carry uncertainty. For that we need a different approach: instead of tracking a single value, track a guaranteed interval that the true answer must lie within. That's the subject of the next article.