Let
Where
Compute
given that is a prime number
First letβs write this special factorial explicitly
The number
Now letβs first divide the equation by
If we apply the modulo operation to each term except the multiples of
NOTE: weβre not applying the modulo operator to each multiple of
NOTE: the number
We see that the expression
Since each
Note that the term multiplying
This observation leads to a recursive implementation
Complexity:
long long special_factorial_mod_p(long long n, long long p) {
long long res = 1;
// computation of c
long long c = p-1;
while (n > 1) {
res = (res * binary_exponentiation_modulo_m(c, n / p, p)) % p;
for (long long i = 2; i <= n % p; i += 1) {
res = (res * (long long)i) % p;
}
n /= p;
}
return res % p;
}
Applications
Finding the value of
We can quickly calculate the value of
Which means that
NOTE:
The denominator can be found using the modular multiplicative inverse of
long long nCr_mod_p(int n, int r, int p) {
int a = max_power_in_factorial(n, p);
int b = max_power_in_factorial(n - r, p);
int c = max_power_in_factorial(r, p);
if (a > b + c) {
return 0;
}
return (special_factorial_mod_p(n, p) *
((modular_multiplicative_inverse(special_factorial_mod_p(n - r, p), p) *
modular_multiplicative_inverse(special_factorial_mod_p(r, p), p)) % p) % p);
}