CSC110 / assignments / a2 / gcd.py
gcd.py
Raw
def a_gcd(n: int, m: int) -> int:
    """Return the greatest common divisor of m and n.

    Preconditions:
    - 1 <= m <= n
    """
    possible_divisors = range(1, m + 1)
    common_divisors = {d for d in possible_divisors if divides(d, n) and divides(d, m)}
    return max(common_divisors)

#
def divides(d: int, n: int) -> bool:
    """Return whether d divides n."""
    if d == 0:
        return n == 0
    else:
        return n % d == 0


def gcd(n: int, m: int) -> int:
    """Return the greatest common divisor of m and n.

    Preconditions:
    - 1 <= m <= n
    """
    r = n % m  # (Sept 30) CORRECTED: Used to be n % d

    if r == 0:
        print(m, 0)
        return m
    else:
        possible_divisors = range(1, r + 1)
        common_divisors = {d for d in possible_divisors if divides(d, n) and divides(d, m)}
        print(max(common_divisors))
        return max(common_divisors)


def a(x, y):
    assert a_gcd(x, y) == gcd(x, y) == gcd(y, x % y)