Keep only the latest
Keep only the latest common divisor
Do we need the list?
We keep a whole list of common divisors, but only use the last one. Each time we find a larger common divisor, the ones we found earlier are useless!
What do we really need to remember while scanning?
What this lesson covers
The idea
Instead of a list, track the most recent common divisor, starting at 1 and updating it for each k from 2 to min(m, n) dividing both; it ends as the gcd.
Do we need the list?
We keep a whole list of common divisors, but only use the last one. Each time we find a larger common divisor, the ones we found earlier are useless!
What do we really need to remember while scanning?
- Only the most recent common divisor
- Every common divisor found so far
- Every number checked so far
Track one number
most-recent-common-divisor starts at 1 (1 is always a common divisor). For each k from 2 to min(6, 12) = 6: if k divides both 6 and 12, update most-recent-common-divisor to k.
One value is enough
Instead of a list, track the most recent common divisor: start at 1, and update it for each k from 2 to min(m, n) that divides both. At the end it is the gcd.
Book's example, m = 6, n = 12: k = 2 divides both → 2; k = 3 → 3; k = 4 does not divide 6 → stays 3; k = 5 → stays 3; k = 6 divides both → 6. So gcd(6, 12) = 6.
Notes
No lists needed: most-recent-common-divisor = 1; for k = 2 … min(m, n), if k divides both, set it to k. It ends as the gcd.
Check yourself
In the scan for gcd(6, 12), k = 4. What happens?
Run the same scan for gcd(375, 825). What is most-recent-common-divisor at the end?
Answer: 75
The last k that divides both is 75, so most-recent-common-divisor ends at 75 = gcd(375, 825).
Before the scan starts, most-recent-common-divisor is set to which number?
Answer: 1
It starts at 1, because 1 divides every number.
- 4 does not divide 6, so most-recent-common-divisor stays 3 — correct. Yes.
- It becomes 4, since 4 divides 12. k must divide both 6 and 12.
- It goes back to 1. It only ever changes to a new common divisor.