Extended Euclidean algorithm to find modular inverse