Robust function for n factorial
Question
Write a routine that computes and discuss what can go wrong.
Short answer
Loop multiplying in , with guards. Reject negative input and return for . Overflow is the main issue: is the largest that fits in a 64-bit integer and the largest finite double, so use big integers or work with (e.g. lgamma) when values get large. Recursion works but adds stack depth for no gain.
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.13, p.158; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solution