Learn
Factorial with Modular Arithmetic
A factorial of (written ) is the product of all positive integers up to . When factorials grow large, you compute the result modulo to prevent overflow.
Factorial values grow quickly. For , you already exceed . You can take the modulo at each step because .
text
function factorial(n, mod):
result = 1
for i from 1 to n:
result = (result * i) mod mod
return result
Precomputation: If you need factorials for multiple queries, precompute them in an array:
text
function precomputeFactorials(maxN, mod):
fact = array of size maxN + 1
fact[0] = 1
for i from 1 to maxN:
fact[i] = (fact[i-1] * i) mod mod
return fact
Applications: You use factorials for permutations, combinations, probability calculations, and counting problems in combinatorics.
Time complexity: for a single factorial computation.
Space complexity: for iterative approach, if precomputing an array.