How to calculate $N! \mod P$ fast?

168 Views Asked by At

Given numbers $N$ and $P$. Calculate $\:N! \mod P$.

$N$ and $P$ are very large so that I can't calculate it by using Fermat's little theorem directly.

But $|N - P|$ is small($\le 1000$) so I can solve it by using Wilson's theorem.

When $N < P$, $$(\prod_{i = n + 1}^{P - 1}{i})^{-1} \times (P - 1)\mod\ P$$ is the answer.

And I want to know how I can solve it faster when $|N - P|$ gets larger.

Thanks.