ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Theory of numerical algorithms

The headers of include/ADS/numeric realize the arithmetic of section 2.6 and of section 12.3 of the book (the integers of \( n \) bits and the polynomials, multiplied by divide et impera), the product of matrices of section 12.4, the recurrences of chapter 13 (the numbers of Fibonacci, the binomial coefficients, the chain of matrices) and the numbers of Catalan of the exercises on dynamic programming, the number theory of chapter 17 (Euclid, the modular powers, the test of Miller and Rabin, RSA), and, beyond the book, the integers and the fractions of any length, the generators of random numbers with their tests and the samplings, and the sparse matrices. This page collects what the headers take for granted: the notation shared by all of them (see Definitions and notation), the representations of the numbers and of the matrices with the costs of their operations (see Representations and their costs), and, for each family of algorithms, the property on which its correctness rests and the argument behind its bound (from Divide et impera on the products to Sparse matrices), and the backends of GMP and of a CBLAS on which some of them run (see The backends of GMP and of a CBLAS). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.

Definitions and notation

An integer is written in a base \( \beta \) as the digits \( x_0 , x_1 , \ldots , x_{n-1} \in [ 0 , \beta ) \), the least significant first, i.e., \( x = \sum_{i<n} x_i \beta^i \); the base is 2 for the vectors of bits of BinaryInteger.h and \( 2^{64} \) for the digits (the limbs) of BigInteger.h, and the length \( n \) of the operands is the measure of the costs. A polynomial is the vector of its coefficients from the constant one, so that the product of two integers is the product of their polynomials in \( x = \beta \) followed by the propagation of the carries. A matrix is \( m \times n \), and a sparse one has \( \mathit{nnz} \) nonzero entries, the others being 0 and not stored.

The symbols of the headers of the area
SymbolMeaning
\( n \), \( \beta \)the number of digits (bits, coefficients, rows) of an operand, and the base of the digits
\( M( n ) \)the time of the product of two integers of \( n \) digits, in which the quotients, the roots, the conversions and the gcds are measured
\( \gcd( a , b ) \), \( a \bmod m \)the greatest common divisor, and the remainder in \( [ 0 , m ) \)
\( \omega_n \)a root of unity of order \( n \) modulo a prime, that of the transform \( \hat a_k = \sum_{j<n} a_j \omega_n^{j k} \)
\( F_n \), \( C_n \), \( \binom{n}{k} \)the numbers of Fibonacci (\( F_0 = F_1 = 1 \)) and of Catalan, and the binomial coefficients
\( \mathit{nnz} \)the nonzero entries of a sparse matrix
\( g \), \( U \)a generator of random words, and a real uniform in \( [ 0 , 1 ) \) or \( ( 0 , 1 ) \)

Representations and their costs

The numbers and the matrices of the area are kept in several representations, each with the operations that it makes cheap; the table gives the space and the cost of the main ones (the products of the integers of any length depend on their length, see Divide et impera on the products).

The representations of the area and the cost of their operations
RepresentationSpaceMain operations
Bits of BinaryInteger.h\( \Theta( n ) \)sum \( \Theta( n ) \), product \( \Theta( n^2 ) \) or \( \Theta( n^{\log_2 3} ) \)
BigInteger\( \Theta( n ) \) digits of 64 bitssum \( \Theta( n ) \), product from \( \Theta( n^2 ) \) to \( O( n \log n ) \), quotient, conversion and gcd \( O( n^2 ) \) by the code of the book, those of GMP on its backend
Rationaltwo BigInteger in lowest termseach operation a few products and gcds of the terms
Matrix, DenseMatrix\( \Theta( m n ) \)product \( \Theta( n^3 ) \), or \( O( n^{2.81} ) \) by Strassen
SparseMatrix\( \Theta( m + n + \mathit{nnz} ) \)entry \( O( \text{its row} ) \), insertion and deletion of an entry \( O( \text{its row and column} ) \)
CsrMatrix, SellMatrix\( \Theta( m + \mathit{nnz} ) \), the padding for SELLproduct by a vector \( \Theta( m + \mathit{nnz} ) \), transpose \( \Theta( m + n + \mathit{nnz} ) \)
DynamicCsr\( \Theta( m + \mathit{nnz} ) \)append of a row linear in its entries, removal of rows in one pass

The orthogonal lists of SparseMatrix are preferable when the pattern of the nonzeros changes, as in the elimination by pivots, whose fill-in enters the lists where it appears; the compressed rows are preferable when the pattern is fixed and the matrix is read, since a product by a vector then streams the values and the columns from memory in one pass. Among the dense representations, the vector of rows of Matrix follows the book, while DenseMatrix keeps the entries in one block, the layout by rows of the CBLAS, to which gemm() hands its products when there is one.

Divide et impera on the products

The sum of two integers of \( n \) digits costs \( \Theta( n ) \), a bound that cannot be improved since every digit must be read; the product of the school costs \( \Theta( n^2 ) \), one partial product per digit of a factor. With \( a = a_1 \beta^h + a_0 \) and \( b = b_1 \beta^h + b_0 \), \( h = \lfloor n / 2 \rfloor \), the product is

\[ a b = a_1 b_1 \beta^{2h} + ( a_1 b_0 + a_0 b_1 ) \beta^h + a_0 b_0 , \tag{1} \]

four products of half size and \( \Theta( n ) \) sums, whence \( T( n ) = 4 T( n / 2 ) + \Theta( n ) = \Theta( n^2 ) \), no gain (multiplyFour() of Polynomial.h, the Prodotto4() of section 2.6).

Lemma 1 (Karatsuba). The middle term of (1) is

\[ a_1 b_0 + a_0 b_1 = ( a_1 + a_0 ) ( b_1 + b_0 ) - a_1 b_1 - a_0 b_0 , \tag{2} \]

so that three products of half size suffice, and \( T( n ) = 3 T( n / 2 ) + \Theta( n ) = \Theta( n^{\log_2 3} ) \), with \( \log_2 3 < 1.59 \).

Indeed, (2) is an identity of the polynomials, and the recursion tree of \( T \) has \( 3^k \) calls of size \( n / 2^k \) at the level \( k \), whose total work \( ( 3 / 2 )^k n \) grows geometrically with \( k \); the leaves, \( 3^{\log_2 n} = n^{\log_2 3} \) of them, dominate. The same argument gives the bound of every split of this kind: a product cut in \( k \) pieces and rebuilt from \( r \) products of the pieces costs \( \Theta( n^{\log_k r} ) \) when \( r > k \). Hence Toom-3, five products of a third (the values of the polynomials at \( 0 , \pm 1 , 2 , \infty \) and an interpolation), costs \( \Theta( n^{\log_3 5} ) = O( n^{1.47} ) \), and Toom-4, seven of a quarter, \( \Theta( n^{\log_4 7} ) = O( n^{1.41} ) \), with constants that grow with \( k \). The code of the book in BigInteger passes from the school to Karatsuba at kKaratsuba digits and to a convolution of the digits at kFFT, round lengths that no processor tuned, while GMP, its backend, adds the methods of Toom and chooses its own thresholds; the convolution is computed by the number theoretic transform in \( O( n \log n ) \) operations (see The number theoretic transform).

The matrices obey the same scheme. The product of two \( n \times n \) matrices by the definition costs \( \Theta( n^3 ) \), and by blocks of \( n / 2 \) it is eight products of blocks, again \( \Theta( n^3 ) \); Strassen rebuilds it from seven products and eighteen sums of blocks (Winograd's variant, of DenseMatrix.h, from seven and fifteen), whence

\[ T( n ) = 7 T( n / 2 ) + \Theta( n^2 ) = \Theta( n^{\log_2 7} ) , \qquad \log_2 7 < 2.81 . \tag{3} \]

The price is the accuracy in floating point: the bound of the error grows with a power of \( n / n_0 \), \( n_0 \) the size at which the recursion stops, instead of with \( n \) (Higham), which is the reason why multiplyStrassen() stops early and leaves the blocks to gemm().

The products of the area
FunctionMethodTime
multiplyNaive(), multiplyBinarySchool()the school\( \Theta( n^2 ) \)
multiplyFour(), multiplyBinaryFour()(1), four halves\( \Theta( n^2 ) \)
multiplyKaratsuba()(2), three halves\( \Theta( n^{\log_2 3} ) \)
BigInteger::operator*()school, Karatsuba, the NTT, or GMP\( O( n \log n ) \) for the longest
multiplyNaive() and strassen() of Matrix.hthe definition, and (3)\( \Theta( n^3 ) \), \( \Theta( n^{\log_2 7} ) \)
gemm(), multiplyStrassen()the definition by blocks, or the CBLAS, and (3) down to gemm()\( \Theta( m n k ) \), \( O( n^{\log_2 7} ) \)

The quotient, the square root and the conversions between the bases reduce to products. The quotient of Algorithm D of Knuth guesses each digit from the leading digits of the remainder and of the normalized divisor, a guess that exceeds the true digit by at most 2 (by 1 with three digits over two), and costs \( O( m n ) \) for a quotient of \( m \) digits, the method of the code of the book; Newton's method on the reciprocal, \( x \gets x + x ( 1 - b x ) \), doubles the correct digits at each step, so that the reciprocal, and with it the quotient, costs a constant number of products of the final length, \( O( M( n ) ) \), the steps on the shorter lengths summing to a geometric series, and the conversions that split the number by a power of the base near its square root cost \( O( M( n ) \log n ) \): these are the methods of GMP, while the code of the book converts by one short division per word, \( O( n^2 ) \). The gcd of Lehmer, which applies to the whole numbers the quotients found on their leading digits, spares all but one long operation per word of quotients (see the comments of BigInteger.h).

Recurrences and dynamic programming

The numbers of Fibonacci, \( F_n = F_{n-1} + F_{n-2} \), computed by the recurrence as it is written, take a number of calls that satisfies the same recurrence, i.e., \( \Theta( \phi^n ) \) with \( \phi = ( 1 + \sqrt{5} ) / 2 \approx 1.6 \); the table of the values already computed, or the last two alone, take \( O( n ) \) (fibonacci() of Combinatorics.h). The same holds for the binomial coefficients:

\[ \binom{n}{k} = \binom{n-1}{k-1} + \binom{n-1}{k} , \qquad \binom{n}{0} = \binom{n}{n} = 1 , \tag{4} \]

whose recursion makes \( 2 \binom{n}{k} - 1 \) calls (each leaf returns 1, and a tree with \( \ell \) leaves whose inner nodes have two children has \( 2 \ell - 1 \) nodes), against the \( \Theta( n^2 ) \) of the triangle of Tartaglia (tartaglia()), which fills (4) by rows.

The numbers of Catalan count the binary trees: a tree of \( n \) nodes has a left subtree of \( k \) nodes and a right one of \( n - 1 - k \), and hence

\[ C_0 = 1 , \qquad C_n = \sum_{k=0}^{n-1} C_k C_{n-1-k} , \tag{5} \]

filled in \( \Theta( n^2 ) \) operations by catalan(); \( C_n = \binom{2n}{n} / ( n + 1 ) \sim 4^n / ( n^{3/2} \sqrt{\pi} ) \), so that the parenthesizations of a product of \( n \) matrices, which are \( C_{n-1} \), cannot be enumerated. The chain of matrices (matrixChain()) has optimal substructure instead: the last product of an optimal order splits the chain at some \( k \), and both sides are then ordered optimally, whence the recurrence (section 13.3)

\[ \mathit{DP}[ i ][ j ] = \min_{i \le k < j} \{ \mathit{DP}[ i ][ k ] + \mathit{DP}[ k + 1 ][ j ] + c_i c_{k+1} c_{j+1} \} , \tag{6} \]

\( \Theta( n^2 ) \) subproblems of \( O( n ) \) choices each, i.e., \( O( n^3 ) \) time, filled by increasing length so that the two sides are known when a chain is solved.

Number theory

Lemma 2 (Euclid). For \( m > 0 \),

\[ \gcd( s , m ) = \gcd( m , s \bmod m ) , \tag{7} \]

and the algorithm that applies (7) until \( m = 0 \) makes \( O( \log m ) \) steps.

Indeed, \( s \bmod m = s - \lfloor s / m \rfloor m \), so that the two pairs have the same common divisors. After two steps the pair \( ( s , m ) \) has become \( ( r , m \bmod r ) \), \( r = s \bmod m \), and \( r < s / 2 \): if \( m \le s / 2 \), since \( r < m \), and otherwise since \( r = s - m \); hence the first number halves every two steps, and the worst case is that of two consecutive numbers of Fibonacci (Lamé). extendedEuclid() carries along the coefficients of Bezout: if \( m p' + ( s \bmod m ) q' = d \), then \( s q' + m ( p' - \lfloor s / m \rfloor q' ) = d \), and when \( d = 1 \) the coefficient of \( s \) is its inverse modulo \( m \) (modInverse()). The binary gcd of Stein (binaryGcd()) replaces the divisions by shifts and subtractions, since \( \gcd( a , b ) = \gcd( \min( a , b ) , | a - b | ) \) and the difference of two odd numbers is even; each step halves the larger number at least, and the steps are at most \( \log_2 a + \log_2 b + 2 \).

The power \( x^v \bmod m \) by repeated squaring (powMod(), exercise 17.1) reads the bits of \( v \): with \( v = \sum_i v_i 2^i \), \( x^v = \prod_{i : v_i = 1} x^{2^i} \), the factors \( x^{2^i} \) are squares of one another, and the time is \( \lfloor \log_2 v \rfloor + 1 \) squarings and at most as many products modulo \( m \). The products modulo an odd \( m \) go by the form of Montgomery, \( \bar x = x R \bmod m \), \( R = 2^{64} \), in which the reduction of \( T = \bar a \bar b < m R \) is

\[ \mathrm{REDC}( T ) = \frac{T - q m}{R} \equiv T R^{-1} \pmod{m} , \qquad q = T m^{-1} \bmod R , \tag{8} \]

exact since \( T - q m \equiv 0 \pmod{R} \), and in \( ( -m , m ) \), so that one addition of \( m \) at most ends it: two products and no division (Montgomery64).

Theorem 3 (Miller and Rabin). Let \( n > 2 \) be odd and \( n - 1 = 2^v m \) with \( m \) odd. If \( n \) is prime, every base \( b \in [ 1 , n ) \) satisfies

\[ b^m \equiv 1 \quad \text{or} \quad b^{2^i m} \equiv -1 \pmod{n} \text{ for some } 0 \le i < v , \tag{9} \]

and if \( n \) is composite at most a quarter of the bases satisfy (9).

The first part holds since \( b^{n-1} \equiv 1 \) (Fermat), and modulo a prime the only square roots of 1 are \( \pm 1 \), so that the sequence \( b^m , b^{2m} , \ldots , b^{2^v m} \) either starts at 1 or reaches 1 right after \( -1 \); the second is the theorem of Rabin, whose proof counts the bases in the group of the units. A base that violates (9) is a witness (witness()), and \( K \) random bases fail to find one for a composite \( n \) with probability at most \( 4^{-K} \) (millerRabin()); the test errs only by saying prime. For \( n \) below \( 2^{64} \) a few fixed bases leave no composite unwitnessed, a fact checked by an exhaustive computation (Jaeschke, Sinclair), which makes isPrime() exact.

RSA rests on Euler's theorem: with \( N = x y \), \( x \) and \( y \) distinct primes, and \( p s \equiv 1 \pmod{( x - 1 ) ( y - 1 )} \), one has \( M^{p s} \equiv M \pmod{N} \) for every \( M < N \), since the congruence holds modulo \( x \) and modulo \( y \) (by Fermat if the prime does not divide \( M \), trivially if it does); hence the decryption \( C^s \) undoes the encryption \( M^p \) (section 17.3). The sieve of Eratosthenes (sieve()) removes the multiples of each prime \( p \le \sqrt{n} \) from \( p^2 \) on, the smaller ones being multiples of smaller primes already removed, in \( \sum_{p \le n} n / p = O( n \log \log n ) \) time by the theorem of Mertens.

The number theoretic transform

Let \( p \) be a prime with \( n \mid p - 1 \), and \( \omega_n \) an element of order \( n \) modulo \( p \). The transform of \( a_0 , \ldots , a_{n-1} \), \( \hat a_k = \sum_j a_j \omega_n^{j k} \bmod p \), evaluates the polynomial \( a( x ) = \sum_j a_j x^j \) at the \( n \) roots of unity \( \omega_n^k \), and the inverse interpolates it, with \( \omega_n^{-1} \) and a factor \( n^{-1} \bmod p \), since \( \sum_k \omega_n^{j k} \equiv 0 \) unless \( n \mid j \).

Lemma 4 (the convolution). If \( c \) is the cyclic convolution of \( a \) and \( b \), \( c_k = \sum_{j} a_j b_{( k - j ) \bmod n} \), then

\[ \hat c_k = \hat a_k \hat b_k \quad \forall k . \tag{10} \]

Indeed, \( c( x ) \equiv a( x ) b( x ) \) modulo \( x^n - 1 \), and each \( \omega_n^k \) is a root of \( x^n - 1 \). With \( n \) at least the number of coefficients of the product, and \( p \) (or the product of the primes, by the Chinese remainder theorem) above its largest coefficient, the convolution is the product of the polynomials exactly, and that of the integers once the carries are propagated (the NTT of BigInteger.h).

The transform is fast because it factors. With \( n = r m \), the index \( j = r i + j' \) of the input and \( k = k' + m q \) of the output, one has

\[ \hat a_{k' + m q} = \sum_{j'<r} \omega_r^{j' q} \, \omega_n^{j' k'} \sum_{i<m} a_{r i + j'} \omega_m^{i k'} , \tag{11} \]

i.e., \( r \) transforms of length \( m \), \( n \) products by the twiddles \( \omega_n^{j' k'} \), and \( m \) transforms of length \( r \) (Cooley and Tukey). Applied recursively to \( n = 2^K \) with \( r = 2 \), the rounds of butterflies of BigInteger.h, (11) gives \( T( n ) = 2 T( n / 2 ) + \Theta( n ) = \Theta( n \log n ) \), against the \( \Theta( n^2 ) \) products of the definition (sections 4.3.3 and 4.6.4 of Knuth).

Random numbers and samplings

A linear congruential generator \( X_{k+1} = ( a X_k + c ) \bmod m \) (LinearCongruential) has a period at most \( m \), and exactly \( m \) if and only if \( c \) and \( m \) are coprime, \( a - 1 \) is a multiple of every prime factor of \( m \), and of 4 if \( m \) is (Hull and Dobell); its pairs \( ( X_k , X_{k+1} ) \) lie on lines at the distance \( 1 / \nu_2 \), and the spectral test (spectralTest2()) measures \( \nu_2 \) by the reduction of a basis of the lattice of the vectors \( ( u , v ) \) with \( u + a v \equiv 0 \pmod{m} \); the same generator with \( a , c , m \) fixed at compile time (LinearCongruentialT, of which MinStd and Mmix) has min() and max() constant, as the distributions of the standard library require. The generators of RandomGenerators.h replace the linear map modulo \( m \) with linear maps over \( \mathbb{F}_2 \) (xoshiro) or with the rounds of a bijection on a counter (Philox), followed by a nonlinear output. The empirical tests compare the counts \( Y_s \) of \( k \) categories of probabilities \( p_s \) with the expected ones,

\[ V = \sum_s \frac{( Y_s - n p_s )^2}{n p_s} , \tag{12} \]

which for large \( n \) follows the \( \chi^2 \) distribution with \( k - 1 \) degrees of freedom (chiSquare(), serialTest()).

Lemma 5 (the shuffle). The shuffle of Fisher and Yates, which for \( j = n , n - 1 , \ldots , 2 \) swaps the item \( j - 1 \) with one drawn uniformly among the first \( j \), gives each of the \( n! \) permutations with probability \( 1 / n! \).

Indeed, the draws are \( n ( n - 1 ) \cdots 2 = n! \) equally likely sequences, and they give distinct permutations, since the item put in the place \( j - 1 \) is never moved again. The uniform draw below \( j \) is exact only if the generator gives it so: uniformBelow() takes the high word of \( x j \) and rejects the low words below \( 2^{64} \bmod j \), which leaves each result \( \lfloor 2^{64} / j \rfloor \) words, while a plain \( x \bmod j \) is off by at most \( j / 2^{64} \) for a generator of 64 bits, and by much more on a narrow range (with the numbers \( 1 , 2 , 3 \) and \( j = 2 \), one index comes twice as often as the other); shuffle() and reservoirSampling() of RandomNumbers.h draw by the method of Lemire on a full word; on a range of \( r + 1 < 2^{64} \) numbers with \( j \le r + 1 \), they take \( \lfloor x / q \rfloor \) with \( q = \lfloor ( r + 1 ) / j \rfloor \) and reject the \( x \ge q j \), and with \( j > r + 1 \) they take \( ( r + 1 ) y + x \), \( y \) drawn in the same way below \( \lceil j / ( r + 1 ) \rceil \), and reject the results from \( j \) on, so that they are exact on any generator.

Lemma 6 (the reservoir). If the item \( t \) of a stream, \( t > n \) (from 1), replaces a uniform item of a reservoir of \( n \) with probability \( n / t \), then after \( N \) items each of them is in the reservoir with probability \( n / N \).

By induction on \( N \): an item in the reservoir after \( N - 1 \) items, with probability \( n / ( N - 1 ) \), survives the item \( N \) with probability \( 1 - ( n / N ) ( 1 / n ) = ( N - 1 ) / N \), and the product is \( n / N \). Algorithm R (reservoirSampling()) draws a number per item, while Algorithm L of Li (reservoirSampleL()) draws how many items to skip, a geometric number, and only \( O( n ( 1 + \log( N / n ) ) ) \) numbers in all; when \( N \) is known, the selection of each item with probability \( ( n - s ) / ( N - t ) \), \( s \) the items taken among the \( t \) seen, is uniform for the same reason (Algorithm S), and the method of Vitter draws its gaps (sampleBySkips()). The alias method (AliasTable) draws from a discrete distribution in \( O( 1 ) \): each of \( n \) cells of equal probability holds an item with a share \( p_i \le 1 \) and an alias for the rest, which the construction of Vose makes possible since the shares below 1 and above 1 always balance.

Sparse matrices

The product \( y = A x \) of a matrix in compressed sparse rows reads each nonzero once with the column that addresses \( x \), in \( \Theta( m + \mathit{nnz} ) \) time, and its \( 2 \, \mathit{nnz} \) operations on \( 12 \, \mathit{nnz} \) bytes make it bound by the bandwidth of the memory rather than by the processor (12 bytes for a double and a column of 32 bits; BasicCsrMatrix takes the types of the values, of the columns and of the offsets, e.g., int for both, the arrays that Eigen and GraphBLAS read without a copy). The transpose is the matrix by columns, built by a counting sort on the columns: the counts give the starts of the rows of the transpose, and the nonzeros, scanned by row, land in each row of the transpose by increasing row, so that it comes out sorted in \( \Theta( m + n + \mathit{nnz} ) \) (transpose() of CsrMatrix); the same counting sort, by the major index, assembles the compressed form from triplets in any order (SparseAssembly.h). The format SELL- \( C \)- \( \sigma \) (SellMatrix) stores the rows by chunks of \( C \), column by column, so that the vector lanes compute \( C \) rows at once; its cost is that of the padding, \( \sum_c C \max_{i \in c} r_i - \mathit{nnz} \), which the sort of the rows by length within windows of \( \sigma \) keeps small.

The pivot step on the orthogonal lists (pivot() of SparseMatrix) is the elimination by exchange of Knuth: with the pivot \( a \) in the row \( r \) and the column \( c \), every entry \( d \) with a nonzero \( b \) in the pivot row and \( c' \) in the pivot column becomes \( d - b c' / a \), the pivot row is divided by \( a \) and the pivot column by \( - a \), and the pivot becomes \( 1 / a \); a pivot on each diagonal place in turn inverts a matrix whose pivots are not zero. Only the entries in the rows of the pivot column and in the columns of the pivot row change, and the new nonzeros (the fill-in) enter the lists where they appear.

The backends of GMP and of a CBLAS

Where a mature library computes the same function, the headers of the area hand the operation to it, at every size, instead of keeping kernels of their own that each processor and each version of the library would call to be tuned again: BigInteger and Rational run on GMP when ADS_WITH_GMP is defined, and gemm() of double and float on a CBLAS (OpenBLAS, the reference CBLAS, Accelerate) when ADS_WITH_BLAS is; CMake and the makefile define each macro whenever the library is found, and leave it undefined otherwise. Likewise, with ADS_WITH_BOOST defined and Boost 1.86 or later, Xoshiro256 and Xoshiro256StarStar are the generators of Boost.Random, seeded as those of ADS and hence giving the same numbers. The dispatch is therefore the presence of the backend alone, with no threshold of length: the library chooses its own algorithms for the processor it was built for. Without the backend, as on a compiler for which none is installed, the headers run the algorithms of the book, written for clarity and portability with no assembly, no vector instructions and no constant measured on a processor: Algorithms A, S, M and D of Knuth, Karatsuba and the number theoretic transform for the long products, the conversions of section 4.4 and the gcd of Lehmer for the integers, and the product of the definition by blocks for the matrices; the same code is the reference that the tests compare the backend with.

Lemma 7 (the backends change no result). For every operation of BigInteger and Rational, the result on the backend equals that of the code of ADS; for gemm(), both compute \( \alpha A B + \beta C \) by the classical product, each entry a sum of \( k \) products in some order, so that both satisfy

\[ | \hat C - ( \alpha A B + \beta C ) | \le \gamma_{k + 2} \, ( | \alpha | | A | | B | + | \beta | | C | ) , \qquad \gamma_j = \frac{j u}{1 - j u} , \tag{13} \]

with \( u \) the unit roundoff, though the two results may differ in the last bits.

Indeed, the integers and the fractions of GMP are exact, as are those of ADS, and a fraction in lowest terms with a positive denominator is unique, so that the two routes return the same digits; the views of GMP on the digits of a BigInteger (mpz_roinit_n()) read them in place, both being sequences of words of 64 bits from the least significant, and the results are written into the digits of the result, or copied into them from a number of GMP, in \( O( n ) \) time, below the cost of the operation itself (the copy is the price of the representation). For the matrices, (13) is the bound of the classical product whatever the order of the sums (Higham, section 3.5), which differs between the loops of ADS and the kernels of the CBLAS; hence the tests compare the products on small integers, which both compute exactly, and the others within (13).

References

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, sections 2.6, 12.3 and 12.4 and chapters 13 and 17, https://algoritmicamente.it/materiali/libro/capitoli/cap12.pdf
D. E. Knuth, The Art of Computer Programming, vol. 2, Seminumerical Algorithms, 3rd ed., Addison-Wesley, 1998, chapters 3 and 4
A. Karatsuba, Yu. Ofman, Multiplication of multidigit numbers on automata, Soviet Physics Doklady 7, 595-596, 1963
V. Strassen, Gaussian elimination is not optimal, Numerische Mathematik 13(4), 354-356, 1969, doi:10.1007/BF02165411
R. P. Brent, P. Zimmermann, Modern Computer Arithmetic, Cambridge University Press, 2010
N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, doi:10.1137/1.9780898718027
J. W. Cooley, J. W. Tukey, An algorithm for the machine calculation of complex Fourier series, Mathematics of Computation 19(90), 297-301, 1965, doi:10.1090/S0025-5718-1965-0178586-1
P. L. Montgomery, Modular multiplication without trial division, Mathematics of Computation 44(170), 519-521, 1985, doi:10.1090/S0025-5718-1985-0777282-X
G. L. Miller, Riemann's hypothesis and tests for primality, Journal of Computer and System Sciences 13(3), 300-317, 1976, doi:10.1016/S0022-0000(76)80043-8
M. O. Rabin, Probabilistic algorithm for testing primality, Journal of Number Theory 12(1), 128-138, 1980, doi:10.1016/0022-314X(80)90084-0
R. L. Rivest, A. Shamir, L. Adleman, A method for obtaining digital signatures and public-key cryptosystems, Communications of the ACM 21(2), 120-126, 1978, doi:10.1145/359340.359342
T. E. Hull, A. R. Dobell, Random number generators, SIAM Review 4(3), 230-254, 1962, doi:10.1137/1004061
D. Blackman, S. Vigna, Scrambled linear pseudorandom number generators, ACM Transactions on Mathematical Software 47(4), 36:1-32, 2021, doi:10.1145/3460772
D. Lemire, Fast random integer generation in an interval, ACM Transactions on Modeling and Computer Simulation 29(1), 3:1-12, 2019, doi:10.1145/3230636
J. S. Vitter, Random sampling with a reservoir, ACM Transactions on Mathematical Software 11(1), 37-57, 1985, doi:10.1145/3147.3165
K.-H. Li, Reservoir-sampling algorithms of time complexity \( O( n ( 1 + \log( N / n ) ) ) \), ACM Transactions on Mathematical Software 20(4), 481-493, 1994, doi:10.1145/198429.198435
M. D. Vose, A linear algorithm for generating random numbers with a given distribution, IEEE Transactions on Software Engineering 17(9), 972-975, 1991, doi:10.1109/32.92917
P. Ferragina, Pearls of Algorithm Engineering, Cambridge University Press, 2023, chapter 3 (Random Sampling), doi:10.1017/9781009128933
T. Granlund and the GMP development team, GNU MP: The GNU Multiple Precision Arithmetic Library, version 6.3.0, 2023, https://gmplib.org/gmp-man-6.3.0.pdf
L. S. Blackford, J. Demmel, J. Dongarra, I. Duff, S. Hammarling, G. Henry, M. Heroux, L. Kaufman, A. Lumsdaine, A. Petitet, R. Pozo, K. Remington, R. C. Whaley, An updated set of basic linear algebra subprograms (BLAS), ACM Transactions on Mathematical Software 28(2), 135-151, 2002, doi:10.1145/567806.567807
Y. Saad, Iterative Methods for Sparse Linear Systems, 2nd ed., SIAM, 2003, section 3.4
M. Kreutzer, G. Hager, G. Wellein, H. Fehske, A. R. Bishop, A unified sparse matrix data format for efficient general sparse matrix-vector multiplication on modern processors with wide SIMD units, SIAM Journal on Scientific Computing 36(5), C401-C423, 2014, doi:10.1137/130930352