Lehmer's GCD algorithm explained

Lehmer's GCD algorithm, named after Derrick Henry Lehmer, is a fast GCD algorithm, an improvement on the simpler but slower Euclidean algorithm. It is mainly used for big integers that have a representation as a string of digits relative to some chosen numeral system base, say β = 1000 or β = 232.

Algorithm

Lehmer noted that most of the quotients from each step of the division part of the standard algorithm are small. (For example, Knuth observed that the quotients 1, 2, and 3 comprise 67.7% of all quotients.[1]) Those small quotients can be identified from only a few leading digits. Thus the algorithm starts by splitting off those leading digits and computing the sequence of quotients as long as it is correct.

Say we want to obtain the GCD of the two integers a and b. Let ab.

style \begin{bmatrix}A&B&x\C&D&y\end{bmatrix}

to an extended identity matrix

style \begin{bmatrix}1&0&x\ 0&1&y\end{bmatrix},

and perform the euclidean algorithm simultaneously on the pairs (x + A, y + C) and (x + B, y + D), until the quotients differ. That is, iterate as an inner loop:

style\begin{bmatrix}A&B&x\C&D&y\end{bmatrix}

with the matrix product

style \begin{bmatrix}0&1\ 1&-w\end{bmatrix} \begin{bmatrix}A&B&x\C&D&y\end{bmatrix} =\begin{bmatrix}C&D&y\A-wC&B-wD&x-wy\end{bmatrix}

according to the matrix formulation of the extended euclidean algorithm.

References

  1. [Donald Knuth|Knuth]