Extended euclidean algorithm