Euclid's shortcut
Find the greatest common divisor by taking remainders. About 8 minutes.
The greatest common divisor
You have a floor 48 cm by 18 cm and want square tiles that fit exactly, with no cutting. The biggest tile that works is 6 cm, and that 6 is the greatest common divisor of 48 and 18: the largest number that divides both.
Trying every size from the smaller number downwards works, but for numbers near a trillion it is hopeless.
a = 48, b = 18. 48 % 18 = 12.
Swap in the remainder
Euclid's trick: lay 18 cm tiles along the 48 cm side. Two fit and 12 cm is left over. Anything that fits both 48 and 18 must also fit that leftover 12, so the question shrinks to 18 and 12. Then 12 and 6, then 6 and 0.
When the second number reaches 0, the first one is the answer.
while b != 0:
a, b = b, a % b
return aWhat is the next pair after (35, 15) in Euclid's method?
- A(15, 5)
- B(20, 15)
- C(15, 35)
Show the answer
(15, 5). 35 % 15 = 5, so (a, b) becomes (15, 5). One more round gives (5, 0): the gcd is 5.
Greatest common divisor
Return the greatest number that divides both a and b with no remainder. The numbers can be as large as a trillion, so trying every candidate will be too slow.
a = 48, b = 18 → 6
1 ≤ a, b ≤ 1,000,000,000,000 (use longs)