Skip to content

Robust function for n factorial

Question

Write a routine that computes n!n! and discuss what can go wrong.

Short answer

Loop multiplying 1⋅2⋯n1\cdot2\cdots n in O(n)O(n), with guards. Reject negative input and return 11 for 00. Overflow is the main issue: 20!20! is the largest that fits in a 64-bit integer and 170!170! the largest finite double, so use big integers or work with log⁡n!\log n! (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

Lessons behind this question