Extended Euclidean algorithm.