0
long long x;
for (int i = 1; i <= n; i++) {
    x = (x * i) % m;
}
cout << x;

This is the trick to calculate (n!) mod m (assume m > n). However, I don't know why it's true. Can you explain the math mechanism behind this?

1 Answers1

2

The basic idea here is that you can take the modulus before, during, or after multiplication and get the same value after taking the modulus of the final result.

As @Peter points out,

(a * b) % m == ((a % m) * (b % m)) % m

For the factorial,

n! = 1 * 2 * 3 * ... * (n-1) * n

so we have

n! % m = (((((((1 * 2) % m) * 3) % m) * ... * n-1) % m) * n) % m

taking the modulus after each iteration.


The advantage to doing it this way is that your number won't blow up and overflow your long long type like it would do pretty quickly if you didn't take intermediate modulus values.

Alexis Olson
  • 38,724
  • 7
  • 42
  • 64