def extended_gcd(a, b):
    """
    Calculate extended greatest common divisor of numbers a,b
    :param a: first number
    :param b: second number
    :return: gcd(a,b) and remainders
    """

    def copysign(a, b):
        return a * (1 if b >= 0 else -1)

    lastrem, rem = abs(a), abs(b)
    x, lastx, y, lasty = 0, 1, 1, 0
    while rem:
        lastrem, (quotient, rem) = rem, divmod(lastrem, rem)
        x, lastx = lastx - quotient * x, x
        y, lasty = lasty - quotient * y, y
    return lastrem, copysign(lastx, a), copysign(lasty, b)