‹ Class 9 · Ch 11
The World of Algorithms · Principle 12 of 29

The first gcd algorithm

First algorithm for gcd

Stuck? Ask Guru

NCERT: 11.2.3 First Algorithm for gcd

Think

Putting it together

We now have all the pieces: divisors(n), a common-divisors list, and the rightmost element. Let's put them together into one algorithm and run it on gcd(135, 775) (two of the book's Think and Reflect numbers).

Which step comes first?

What this lesson covers

The idea

Compute divisors of m and of n, collect those in both lists as common divisors, and report the rightmost as gcd(m, n).

Putting it together

We now have all the pieces: divisors(n), a common-divisors list, and the rightmost element. Let's put them together into one algorithm and run it on gcd(135, 775) (two of the book's Think and Reflect numbers).

Which step comes first?

  • Compute divisors(135) and divisors(775)
  • Report the rightmost element
  • Start with the common-divisors list

Run all five steps

Algorithm to find gcd(m, n) 1. Let divisors-of-m be divisors(m). 2. Let divisors-of-n be divisors(n). 3. Start with an empty list common-divisors. 4. For each number x in divisors-of-m: if x also appears in divisors-of-n, add x to common-divisors. 5. Report the rightmost element of common-divisors as gcd(m, n). Steps 1 and 2 are done below. Run steps 3–5.

Five steps

gcd(m, n): compute the divisors of m and of n; collect those in both lists as common-divisors; report the rightmost element as gcd(m, n).

divisors(135) = [1, 3, 5, 9, 15, 27, 45, 135] divisors(775) = [1, 5, 25, 31, 155, 775] common-divisors = [1, 5], so gcd(135, 775) = 5. The book's own run: gcd(375, 825) gives common-divisors [1, 3, 5, 15, 25, 75], so gcd = 75.

Notes

First gcd algorithm: divisors of m, divisors of n, keep those in both as common-divisors, report the rightmost as gcd(m, n).

Check yourself

In step 4, what is x?

Running the algorithm for gcd(135, 775), how many values does step 4 check?

Answer: 8

divisors(135) has 8 values, so step 4 makes 8 membership checks.

What is gcd(135, 775)?

Answer: 5

common-divisors = [1, 5]; the rightmost element is 5.

  • Each divisor of m, taken in turn — correct. Yes. x runs through divisors-of-m.
  • Each number from 1 to n. That is j in the divisors algorithm.
  • The gcd. The gcd is reported only at step 5.