- Lehmer's GCD algorithm
Lehmer's GCD algorithm, named after
Derrick Henry Lehmer , is a rather fast GCDalgorithm , an improvement on the simpler but slowerEuclidean algorithm .Algorithm
Lehmer noted that that most of the
quotient s 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 quotientsKnuth, "The Art of Computer Programming vol 2 "Seminumerical algorithms", chapter 4.5.3 Theorem E.] .)Say we want to obtain the GCD of the two integers "a" and "b". Let "a" ≥ "b".
* If "b" contains only one digit (in the chosen base, say or ), use some other method, such as theEuclidean algorithm , to obtain the result.
* If "a" and "b" differ in the length of digits, perform a division so that "a" and "b" are equal in length, with length equal to "m".
* Iterate until one of "a" or "b" is zero:
** Decrease "m" by one. Let "x" be the leading (most significant) digit in "a", and "y" the leading digit in "b", .
** Initialize a 2 by 3 matrix to an extendedidentity matrix , and perform the euclidean algorithm simultaneously on the pairs and , until the quotients differ. That is, iterate:
*** Compute the quotients "w"1 of the long divisions of ("x" + "A") by ("y" + "C") and "w"2 of ("x" + "B") by ("y" + "D") respectively. Also let "w" be the (not computed) quotient from the current long division in the chain of long divisions of the euclidean algorithm.
*** If "w"1 ≠ "w"2, then break out of the inner iteration. Else set "w" to "w"1 (or "w"2).
*** Set our current matrix::::::: to::::
*** If "B" = 0, we have reached a "deadlock"; perform a normal step of the euclidean algorithm with "a" and "b", and recompute the matrix.
** Set "a" to "aA" + "bB" and "b" to "Ca" + "Db" (again simultaneously). This applies the steps of the euclidean algorithm that were performed on the leading digits in compressed form to the long integers "a" and "b". Restart the outer iteration.References
References
* Kapil Paranjape, [http://www.imsc.res.in/~kapil/crypto/notes/node11.html Lehmer's Algorithm]
Wikimedia Foundation. 2010.