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.
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
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.
Apply what you learned by solving the practice problem for Factorial.
Go to Practice ProblemFactorial values grow quickly. For , you already exceed . You can take the modulo at each step because .
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:
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.