Drill

ProblemsPython › warmup

Greatest common divisor

easywarmupPython

Reducing a fraction, or laying tiles that divide a wall evenly, both come down to the same number.

greatest_common_divisor(first: int, second: int) → int

Solve it in the editor →

Where you start

def greatest_common_divisor(first: int, second: int) -> int:
    

Worked examples

CallResult
greatest_common_divisor(12, 18)6
greatest_common_divisor(17, 5)1
greatest_common_divisor(0, 5)5
greatest_common_divisor(0, 0)0

Hint

Euclid: keep replacing the pair with (second, first mod second) until the second is zero.

Reference solution in Python
def greatest_common_divisor(first: int, second: int) -> int:
    a, b = abs(first), abs(second)
    while b:
        a, b = b, a % b
    return a

The same problem in another language

More warmup problems in Python