Check out this paper (PDF link) by Richard Fateman. The code samples are in Lisp, in but in any event, much of the secret boils down to minimizing the number of bignum (arbitrary precision integer) calculations you have to do.
Naturally, if you don't need/have bignums, it's trivial; either a lookup table or a simple loop will be fine.
EDIT: If you can use an approximate answer, you can either compute the logarithm of the factorial directly by summing log(k)
for k = 2 ... n
, or by using the venerable Stirling approximation. You want to work with the logarithm wherever possible to avoid overflow; in particular, a naive application of Stirling's approximation will overflow in a lot of places where it doesn't have to.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…