Skip to contentKEEP THE CRAFTTHE SANCTUARY

Compute GCD with Euclid

Find the greatest common divisor with Euclid's algorithm: replace (a, b) by (b, a % b) until b is 0.

The problem

Implement greatest_common_divisor(left, right) and return the greatest common divisor of the two integers, the largest number that divides both. The inputs may be negative or zero, but the answer is never negative: greatest_common_divisor(-24, 18) is 6. When one input is 0 the answer is the absolute value of the other, so greatest_common_divisor(0, 9) is 9, and greatest_common_divisor(0, 0) is 0. Use Euclid's algorithm instead of math.gcd.

Starter code

def greatest_common_divisor(left, right):
    pass

Public examples

  1. left = 84, right = 30gives6
  2. left = -24, right = 18gives6

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.