"""Greatest common divisor (Euclid) and least common multiple.

Idea
----
gcd(a, b) == gcd(b, a mod b), because any number dividing both a and b also
divides a - k*b. The remainder shrinks quickly (at least halving every two
steps), so the loop ends after O(log min(a, b)) iterations.

lcm(a, b) = |a * b| / gcd(a, b). Divide before multiplying to keep the
intermediate value small.

The extended version also returns x, y with a*x + b*y = gcd(a, b), which is
how modular inverses are computed.

Complexity
----------
Time:  O(log min(a, b))
Space: O(1)
"""


def gcd(a: int, b: int) -> int:
    """Return the greatest common divisor of ``a`` and ``b`` (always >= 0)."""
    a, b = abs(a), abs(b)
    while b:
        a, b = b, a % b
    return a


def lcm(a: int, b: int) -> int:
    """Return the least common multiple of ``a`` and ``b``."""
    if a == 0 or b == 0:
        return 0
    return abs(a // gcd(a, b) * b)


def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
    """Return ``(g, x, y)`` with ``a * x + b * y == g == gcd(a, b)``."""
    old_r, r = a, b
    old_x, x = 1, 0
    old_y, y = 0, 1
    while r:
        q = old_r // r
        old_r, r = r, old_r - q * r
        old_x, x = x, old_x - q * x
        old_y, y = y, old_y - q * y
    return old_r, old_x, old_y
