All Articles

Modular Arithmetic

xx mod mm is the remainder of xx when xx is divided by mm. It is also represented by the sign %\%. For example, 19 % 4 is 3, since 19 = 4 * 4 + 3.

In many problems, modulo is used since if the answer is very large, modulo m (for example, m=109+7m = 10^9 + 7) will keep the answer <m< m thus fitting it within the primitive data type.

Properties of Modular Arithmetic

(a+b)%m=(a%m+b%m)%m(ab)%m=(a%mb%m+m)%m(a.b)%m=(a%m.b%m)%m(a + b) \%m = (a \%m + b \%m) \% m \\ (a - b) \%m = (a \%m - b \%m + m) \% m \\ (a . b) \%m = (a \%m . b \%m) \% m \\

Modular Multiplicative Inverse

The modular multiplicative inverse of an integer xx such that,

ax1(mod m)ax \equiv 1 (\bmod \space m)
  • The value of xx should be in the range [1,m1][1, m - 1]
  • The multiplicative inverse only exists if a and m are relatively prime

Example

  • a=7a = 7, m=9m = 9. Since (74)%9=1(7 * \underline{4}) \% 9 = 1, 4 is the modulo inverse of 7 under 9.
  • a=5a = 5, m=8m = 8. Since (55)%8=1(5 * \underline{5}) \% 8 = 1, 5 is the modulo inverse of 5 under 8.

Calculation of Modular Multiplicative Inverse

If mm is prime, we can use Fermat’s little theorem to calculate the modulo inverse.

x=a(m2)modmx = a^{(m - 2)} \bmod m

Implementation: Factorial of a Large Number

int factorial(int n, int m) {
    long long ans = 1;

    for (int i = 2; i <= n; ++i) {
        ans = (ans * (long long) i) % m;
    }
    
    return ans % m;
}