C# ModInverse Function

前端 未结 5 1636
梦如初夏
梦如初夏 2020-12-05 19:15

Is there a built in function that would allow me to calculate the modular inverse of a(mod n)? e.g. 19^-1 = 11 (mod 30), in this case the 19^-1 == -11==19;

5条回答
  •  感情败类
    2020-12-05 19:58

    Here is a slightly more polished version of Samuel Allan's algorithm. The TryModInverse method returns a bool value, that indicates whether a modular multiplicative inverse exists for this number and modulo.

    public static bool TryModInverse(int number, int modulo, out int result)
    {
        if (number < 1) throw new ArgumentOutOfRangeException(nameof(number));
        if (modulo < 2) throw new ArgumentOutOfRangeException(nameof(modulo));
        int n = number;
        int m = modulo, v = 0, d = 1;
        while (n > 0)
        {
            int t = m / n, x = n;
            n = m % x;
            m = x;
            x = d;
            d = checked(v - t * x); // Just in case
            v = x;
        }
        result = v % modulo;
        if (result < 0) result += modulo;
        if ((long)number * result % modulo == 1L) return true;
        result = default;
        return false;
    }
    

提交回复
热议问题