This subroutine calculates the multiplicative inverse of a number modulo another one. This is similar to the modinv method in Math::BigInt, but that one seems to be only for big numbers. This one works with friendly small numbers too.

Calling is $b = divmod($a, $m) where $a, $m are two relatively prime integers. Then, $b in an integer so that ($a * $b) % $m == 1.

For example, divmod(17, 26) returns 23, as (17 * 23) % 26 == 1.

Update: modified the subroutine so that it works correctly for negative arguments as well. The error was that I assumed int would calculate the floor for negative numbers too.

use warnings; use strict; sub divmod { my $m = abs($_[1]); my $a = $_[0] % $m; my($b, $x, $y, $n) = ( +$m, 1, 0); while (0 != $a) { $n = int($b / $a); ($a, $b, $x, $y) = ($b - +$n * $a, $a, $y - $n * $x, $x); } $y % $m; }
Here's the previous, wrong version of the code: <S>
# WRONG, DO NOT USE use warnings; use strict; sub divmod { my($a, $m) = @_; my($b, $x, $y, $n) = ($m, 1, 0); while (0 != $a) { $n = int($b / $a); ($a, $b, $x, $y) = ($b - +$n * $a, $a, $y - $n * $x, $x); } $y % $m; }
</s>

In reply to modular inverse by ambrus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.