← LibraryThe Euclidean Algorithm: Classical and Binary VariantsEngineering · MathematicsLesson 215/385← PrevNext →
ArticlePublished 7 Aug 20262 min readBy Kevin JoginEuclidean algorithmGCDbinary GCDStein algorithm

Euclidean Algorithms and Congruences

The Euclidean Algorithm: Classical and Binary Variants

The classical Euclidean algorithm, the binary variant that replaces division with shifts, and how to choose between them.

Engineering / MathematicsEuclidean Algorithms and Congruences2 min readKV-MATH-0513

The greatest common divisor is the single most frequently invoked operation in computational number theory. Two algorithms dominate, and they trade a small number of expensive steps against a large number of cheap ones.

The classical algorithm

Repeatedly replace the pair by the smaller element and the remainder of the division. The process terminates because the remainder strictly decreases.

gcd(a, b) = gcd(b, a mod b), gcd(a, 0) = aEach step requires one multiprecision division.

The binary algorithm

Stein's variant eliminates division entirely, using only subtraction, comparison and shifts. It rests on three observations.

Binary GCD

  1. Extract common twosRemove the largest power of two dividing both; remember it for the end.
  2. Make both oddShift out factors of two from each operand individually.
  3. Subtract and shiftReplace the larger by the difference, then shift out its factors of two.
  4. RepeatContinue until one operand is zero.
  5. RestoreShift the result left by the common power of two.

Choosing between them

Classical versus binary GCD
CriterionClassicalBinary
Operations per stepOne divisionSubtraction and shifts
Number of stepsFewerMore, roughly proportional to bits
Small operandsCompetitiveUsually faster
Large operandsBetter, division amortisesSubtraction count grows
Hardware without fast divisionPoorStrong

Where GCD appears

The operation is ubiquitous: reducing fractions, testing coprimality, detecting factors in Pollard rho and ECM, computing polynomial content, and as the inner loop of Hermite normal form.

Frequently Asked Questions

Why is the Fibonacci case the worst case?
Because consecutive Fibonacci numbers produce a quotient of one at every step, which is the slowest possible reduction. Any larger quotient shrinks the operands faster.

Source. Henri Cohen, A Course in Computational Algebraic Number Theory, Springer GTM 138 — 1.3.1-1.3.2. Structural reference unverified: the source file was not available during authoring; chapter and section numbers are taken from the published edition and have not been checked against a physical copy.

Continue learning

Integer Square Root and Perfect Power DetectionArticle · MathematicsNEXT LESSON →Lehmer's Accelerated GCD ComputationArticle · MathematicsBinary Powering and Exponentiation ChainsArticle · MathematicsThe Extended Euclidean Algorithm and Bezout CoefficientsArticle · Mathematics