Modular Multiplicative Inverse

View as PDF

Submit solution

Points: 7
Time limit: 1.0s
Memory limit: 256M

Problem type

Solve the Modular Multiplicative Inverse problem.

Input Specification

Line 1: N, M (0 \le N < M \le 10^{19}, N is coprime to M)

Note: The values will not fit in a 32 bit integer. They will fit in a 64 bit unsigned integer. For languages that do not have unsigned data types, please use a general big integer.

Output Specification

Line 1: The modular multiplicative inverse of N modulo M. The value should be nonnegative.

Sample Input

2 7

Sample Output



  • 0
    andy_zhu23  commented on Aug. 16, 2021, 8:26 p.m. edited

    Is this problem solvable using Fermat's Little Theorem?

  • 3
    AWB  commented on July 6, 2017, 1:02 p.m.

    I've implemented a variation of XGCD that does not give a coefficient on M, but am having issues with test case #15 and #22. All the rest are AC. Please help.

    • 7
      wleung_bvg  commented on July 6, 2017, 5:13 p.m.

      Try using unsigned long long

      • 0
        Nils_Emmenegger  commented on June 13, 2021, 5:15 p.m.

        If you're still WAing, try signed 128-bit integers (__int128 in C++).

  • 6
    Tan  commented on Aug. 18, 2016, 10:23 p.m.

    Isn't this problem really easy in Java? Java has a built in function for this, which is slow, but still passes.