You can also look at the gmpy module. This is the interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:
>>> import gmpy >>> gmpy.invert(1234567, 1000000007) mpz(989145189)
Updated Answer
As @hyh notes, gmpy.invert() returns 0 if the opposite does not exist. This is consistent with GMP mpz_invert() behavior. gmpy.divm(a, b, m) provides a general solution for a=bx (mod m) .
>>> gmpy.divm(1, 1234567, 1000000007) mpz(989145189) >>> gmpy.divm(1, 0, 5) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: not invertible >>> gmpy.divm(1, 4, 8) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: not invertible >>> gmpy.divm(1, 4, 9) mpz(7)
divm() will return the solution when gcd(b,m) == 1 and throw an exception when the multiplicative inverse does not exist.
Disclaimer: I am the current custodian of the gmpy library.
Updated Answer 2
gmpy2 now correctly throws an exception when the converse does not exist:
>>> import gmpy2 >>> gmpy2.invert(0,5) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: invert() no inverse exists
casevh Jan 26 '11 at 4:13 2011-01-26 04:13
source share