Learnify Academy is a tuition centre in Bahrain. Classes are for students in Bahrain only.Tuition classes in Bahrain only

Greatest common divisor · 2 marks

Let us keep track of a quantity called most-recent-common-divisor. We know that 1 is always a common divisor, so we can start with most-recent-common-divisor set to 1. We then scan all numbers from 2 to min(m, n). For each k from 2 to min(m, n), if k divides both m and n, update most-recent-common-divisor to k. Example: Let m = 6, n = 12.

Answer: min(6, 12) = 6. most-recent-common-divisor goes 1 → 2 (k = 2) → 3 (k = 3) → stays 3 (k = 4, 5) → 6 (k = 6). Scan complete: gcd(6, 12) = 6.

Step-by-step solution

Idea: We do not need a list of all common divisors: each new common divisor is larger than the earlier ones, so we only remember the latest. When the scan ends, the latest common divisor is the greatest.

  1. min(6, 12) = 6, so we scan k = 2, 3, 4, 5, 6. Initially most-recent-common-divisor = 1.½ mark
  2. k = 2 divides both 6 and 12 → update to 2.
    k = 3 divides both 6 and 12 → update to 3.½ mark
  3. k = 4 does not divide 6 → remains 3.
    k = 5 does not divide 6 → remains 3.½ mark
  4. k = 6 divides both 6 and 12 → update to 6. Scan complete. gcd(6, 12) = 6.½ mark
gcd(6, 12) = 6 (most-recent-common-divisor at the end of the scan).

Check: 6 divides 12, so the greatest common divisor of 6 and 12 must be 6 itself ✓.

Answer to write in the exam

min(6, 12) = 6; most-recent-common-divisor = 1

k = 2 divides 6 and 12 → 2

k = 3 divides 6 and 12 → 3

k = 4, 5 do not divide 6 → remains 3

k = 6 divides 6 and 12 → 6

∴ gcd(6, 12) = 6

Common mistakes that cost marks

  • Scanning up to max(6, 12) = 12. A common divisor cannot be larger than the smaller number, so the scan stops at 6.
  • Updating when k divides only one of the numbers (for example k = 4 divides 12 but not 6).
  • Starting with most-recent-common-divisor = 0 instead of 1; if no larger common divisor is found, the answer must still be 1.

How this can come in the exam

MCQ (1 mark)

For m = 8 and n = 20, the values taken by most-recent-common-divisor during the scan are

  1. 1, 2, 4
  2. 1, 2, 4, 8
  3. 2, 4, 5
  4. 1, 4
Show answer

(A) 1, 2, 4
Scan k = 2 to 8. k = 2 and k = 4 divide both 8 and 20; 8 does not divide 20. So 1 → 2 → 4, and gcd(8, 20) = 4.

Try one yourself

Use most-recent-common-divisor to find gcd(9, 15).

Show answer

min = 9; start at 1. k = 2 ✗, k = 3 divides both → 3; k = 4 to 9 ✗ (9 does not divide 15). gcd(9, 15) = 3.

More questions like this

All Algorithms questions · All maths questions