progress

~/problems / Number theory / Primes, divisors and GCD

Greatest common divisor (Euclid)

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write gcd(a, b) -> int: the greatest common divisor of two integers, using Euclid's algorithm. Don't use math.gcd (the tests check).

  • -10^18 <= a, b <= 10^18. The result is never negative, and by convention gcd(0, 0) = 0 and gcd(x, 0) = |x|.
gcd(12, 18)     # 6
gcd(17, 5)      # 1
gcd(0, 9)       # 9
gcd(-12, 18)    # 6
gcd(0, 0)       # 0

Euclid: gcd(a, b) = gcd(b, a mod b), and gcd(a, 0) = |a|. The larger number at least halves every two steps, so it takes O(log) steps.

Subtracting the smaller number one step at a time never finishes when one number is huge and the other small (the tests include gcd(1, 10**18)).

⭐ Bonus: a speed test with 20,000 pairs up to 10^18 earns a star at O(log) steps per call.

Topic: Primes, divisors and GCD. Sieve, trial division to sqrt(n), Euclid's algorithm.

0:00
Ctrl ' run · Ctrl ↵ submit
esc