def Zn_inv(a, n):
    """
    Computes the inverse of a in ℤ_n using the Extended Euclidean algorithm.

    >>> Zn_inv(2, 7)
    4

    >>> Zn_inv(2, 3)
    2

    >>> Zn_inv(2, 256)
    Traceback (most recent call last):
      ...
    ValueError: 2 has no inverse in ℤ_256.
    """
    if a < 0:
        a += n

    t = 0
    r = n
    new_t = 1
    new_r = a

    while new_r != 0:
        quotient = r // new_r
        t, new_t = new_t, t - quotient * new_t
        r, new_r = new_r, r - quotient * new_r

    if r > 1:
        raise ValueError(f'{a} has no inverse in ℤ_{n}.')
    if t < 0:
        t += n

    assert (t * a) % n == 1  # sanity check

    return t