Lehmer's GCD algorithm
From Wikipedia, the free encyclopedia
Lehmer's GCD algorithm is a rather fast GCD algorithm, an improvement on the simpler but slower Euclidean algorithm.
[edit] Algorithm
Lehmer noted that 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. )
Say we want to obtain the GCD of the two integers a and b. Let .
- If b contains only one digit (in the chosen base), use some other method, such as the Euclidean 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.
- Let x be the leading (most significant) digit in a and y the leading digit in b.
- Initialize a square matrix
to the identity matrix
, and iterate:
- Compute the quotients w1 of (x + A)(y + C) and w2 of (x + B)(y + D) respectively. Also let w be the quotient from a/b.
- If w1 = w2, set w to w1 (or w2).
- Set our current matrix
to
- Set x to y and y to x - wy (simultaneously).
- If B = 0, we have reached a deadlock; perform a normal division with a and b, and recompute the matrix. Otherwise, set a to aA + bB and b to Ca + Db (again simultaneously), and iterate.
[edit] References
- ↑ Knuth, The Art of Computer Programming volume 4, section 5.3, Theorem E
- Kapil Paranjape, Lehmer's Algorithm
![]() |
This number theory-related article is a stub. You can help Wikipedia by expanding it. |