title: Fast way to calculate n! mod m where m is prime?
body: <p>I was curious if there was a good way to do this. My current code is something like:</p>
  
  <pre class="lang-python prettyprint-override"><code>def factorialMod(n, modulus):
      ans=1
      for i in range(1,n+1):
          ans = ans * i % modulus    
      return ans % modulus
  </code></pre>
  
  <p>But it seems quite slow!</p>
  
  <p>I also can't calculate n! and then apply the prime modulus because sometimes n is so large that n! is just not feasible to calculate explicitly. </p>
  
  <p>I also came across <a href="http://en.wikipedia.org/wiki/Stirling%27s_approximation" rel="noreferrer">http://en.wikipedia.org/wiki/Stirling%27s_approximation</a> and wonder if this can be used at all here in some way?</p>
  
  <p>Or, how might I create a recursive, memoized function in C++?</p>