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

One scan, not two

Combine the two divisor scans

Stuck? Ask Guru

NCERT: 11.3.1 Improving the Algorithm — Compute both lists of divisors together

Think

Two scans

The first gcd algorithm checks every number from 1 to 375 for divisors of 375, then starts again at 1 and checks every number up to 825 for divisors of 825.

How many possible divisors does it check in all, for gcd(375, 825)?

What this lesson covers

The idea

Scanning j from 1 to max(m, n) once and testing divisibility of both numbers cuts the checks from m + n to max(m, n).

Two scans

The first gcd algorithm checks every number from 1 to 375 for divisors of 375, then starts again at 1 and checks every number up to 825 for divisors of 825.

How many possible divisors does it check in all, for gcd(375, 825)?

  • 375 + 825 = 1200
  • 825
  • 375

Scan once

Run one scan, j = 1 to max(375, 825) = 825. For each j: if j divides 375, add it to the divisors of 375; if j divides 825, add it to the divisors of 825. Count the checks.

m + n becomes max(m, n)

Scan j from 1 to max(m, n) once, testing whether j divides each number. This cuts the checks from m + n to max(m, n).

For gcd(375, 825): two separate scans check 375 + 825 = 1200 numbers; the combined scan checks only 825. Both lists come out the same: [1, 3, 5, 15, 25, 75, 125, 375] and [1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275, 825].

Notes

Combine the scans: one pass of j from 1 to max(m, n), testing both numbers, needs max(m, n) checks instead of m + n.

Check yourself

For gcd(54000, 81000), how many numbers does the combined scan check?

Answer: 81000

max(54000, 81000) = 81000 checks (instead of 135000).

In the combined scan, j = 11. What happens?

  • 11 is added to the divisors of 825 only — correct. Yes. 11 divides 825 (825 = 75 × 11) but not 375.
  • 11 is added to both lists. 11 does not divide 375.
  • Nothing: 11 is skipped. 11 divides 825, so it goes into that list.