Extended Euclidean algorithm