Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You might also want to look at the <a href="http://code.google.com/p/gmpy/" rel="nofollow noreferrer">gmpy</a> module. It is an interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:</p> <pre><code>&gt;&gt;&gt; import gmpy &gt;&gt;&gt; gmpy.invert(1234567, 1000000007) mpz(989145189) </code></pre> <p><strong>Updated answer</strong></p> <p>As noted by @hyh , the <code>gmpy.invert()</code> returns 0 if the inverse does not exist. That matches the behavior of GMP's <code>mpz_invert()</code> function. <code>gmpy.divm(a, b, m)</code> provides a general solution to <code>a=bx (mod m)</code>.</p> <pre><code>&gt;&gt;&gt; gmpy.divm(1, 1234567, 1000000007) mpz(989145189) &gt;&gt;&gt; gmpy.divm(1, 0, 5) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ZeroDivisionError: not invertible &gt;&gt;&gt; gmpy.divm(1, 4, 8) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ZeroDivisionError: not invertible &gt;&gt;&gt; gmpy.divm(1, 4, 9) mpz(7) </code></pre> <p><code>divm()</code> will return a solution when <code>gcd(b,m) == 1</code> and raises an exception when the multiplicative inverse does not exist.</p> <p>Disclaimer: I'm the current maintainer of the gmpy library.</p> <p><strong>Updated answer 2</strong></p> <p>gmpy2 now properly raises an exception when the inverse does not exists:</p> <pre><code>&gt;&gt;&gt; import gmpy2 &gt;&gt;&gt; gmpy2.invert(0,5) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ZeroDivisionError: invert() no inverse exists </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload