liveBook · Manning

Greatest common divisor

As explained in Modern C, Third Edition

The greatest common divisor of two positive integers is the greatest positive integer that divides both of them.

The greatest common divisor (gcd) of positive integers a and b is the greatest positive integer dividing both. Euclid’s algorithm preserves the gcd while replacing the larger argument with the remainder of division. section 7.3

Recursive gcd of 18 and 30

The recursive calls reduce gcd2(18, 30) to gcd2(12, 18), then gcd2(6, 12), and finally return 6 when the remainder becomes zero. section 7.3

inline size_t gcd2(size_t a, size_t b) [[__unsequenced__]] {  1 
  assert(a <= b);               2  
  if (!a) return b;    3  
  size_t r = b % a;            4  
  return gcd2(r, a);     
}

Use the compact C implementation to follow argument ordering, the zero-remainder base case, modulus computation, and recursive descent. section 7.3

How Modern C, Third Edition covers it

How deep it goes
Defines gcd, states two recursive identities, and implements Euclid’s algorithm, while noting that the initial interface assumes valid positive arguments.
Examples
Demonstrates recursive gcd2(18, 30) calls and a C implementation using assertions, remainder calculation, and a zero-remainder base case.
What it assumes
Assumes familiarity with positive integers, divisibility, function calls, assertions, and the modulus operator.
What you can do after
Build it from scratch in C by applying Euclid’s remainder rule recursively to positive integer arguments.
How it connects
Connects greatest common divisor with recursion, Euclid’s algorithm, integer divisibility, and the modulus operation.

Also explained in

Compare how 2 books explain greatest common divisor →

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.