liveBook · Manning

Euclid's algorithm

As explained in Modern C, Third Edition

Euclid's algorithm is an algorithm for computing the greatest common divisor by repeatedly replacing a pair of integers with a smaller equivalent pair.

Euclid's algorithm computes the greatest common divisor (gcd) by preserving the gcd while replacing the input pair with smaller values. For positive integers with a ≤ b, gcd(a,b) = gcd(a,b % a). section 7.3

Recursive C implementation

The recursive function asserts a ≤ b, returns b when a is zero, computes b % a, and recurses with the remainder and a. Starting with 18 and 30 produces the successive pairs (18,30), (12,18), (6,12), and (0,6), yielding 6. section 7.3

TAKEAWAY:

  • Replace the larger operand with the remainder after division by the smaller operand; the gcd remains unchanged. section 7.3
  • Treat the displayed function as a partial interface: it assumes positive inputs and an ordered pair. section 7.3

How Modern C, Third Edition covers it

How deep it goes
Defines gcd, derives subtraction and modulus recurrences, and traces a recursive implementation while stopping short of a full interface.
Examples
Uses gcd2 in C, equations for subtraction and remainder, and the recursive call sequence for gcd2(18,30).
What it assumes
Assumes integer arithmetic and divisibility, while defining gcd and explaining the recursive reduction from zero.
What you can do after
Build it from scratch as a recursive C function for positive, ordered integer inputs.
How it connects
Connects recursion, greatest common divisor, integer division, modulus, and function-call behavior.

Also explained in

Compare how 3 books explain Euclid's algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.