What is the most efficient way to compute factorials modulo a prime?
(This answer was initially posted by the asker jonaprieto inside the question.)

I remember Wilson's theorem, and I noticed little things:

In the above program, it is better if I write:
$$\begin{align}
(p-1)! &amp;\equiv -1 &amp;\pmod p\\
(p-2)! &amp;\equiv (p-1)! (p-1)^ {-1} \equiv \bf{1} &amp;\pmod p\\
(p-3)! &amp;\equiv (p-2)! (p-2)^ {-1} \equiv \bf{(p-2)^{-1}} &amp;\pmod p\\
(p-4)! &amp;\equiv (p-3)! (p-3)^ {-1} \equiv \bf{(p-2)^{-1}} \bf{(p-3)^{-1}} &amp;\pmod p\\
\ (p-5)! &amp;\equiv (p-4)! (p-4)^ {-1} \equiv \bf{(p-2)^{-1}} \bf{(p-3)^{-1}}\bf{(p-4)^{-1}}  &amp;\pmod p\\
\end{align}$$

And you can find $(p-i)^{-1}$ because $\operatorname{gcd}(p, p-i) = 1$, so with the extended Euclidian algorithm you can find the value of $(p-i)^{-1}$, that is the inverse modulus.

You can view the same congruences too,  like to:
$$\begin{align*}
(p-5)! &amp;\equiv (p-24)^{-1}&amp;\pmod p\\
(p-4)! &amp;\equiv (p+6)^{-1}&amp;\pmod p\\
(p-3)! &amp;\equiv (p-2)^{-1} &amp;\pmod p\\
(p-2)! &amp;\equiv 1&amp;\pmod p\\
(p-1)! &amp;\equiv -1&amp;\pmod p\\
\end{align*}
$$ 
so, the sum is equal: $$ (-24)^{-1}+(6)^{-1} +(-2)^{-1}$$
and if you factorize in the beginning the factorials you get 
$$ 8\cdot (-24)^{-1} \pmod p$$
And, voila, inverse modulus is more efficient than factorials.