Learning Objectives
By the end of this lesson you will be able to:
- Explain why factorial values grow so fast they exceed data type limits quickly
- Calculate which factorial values trigger Int32 and Int64 overflow
- Use factorial calculation as a systematic overflow stress test
Why Factorial?
Factorial (n!) multiplies all integers from 1 to n:
- 5! = 120
- 10! = 3,628,800
- 12! = 479,001,600
- 13! = 6,227,020,800 — exceeds Int32 max (2,147,483,647)
- 20! = 2,432,902,008,176,640,000
- 21! = 51,090,942,171,709,440,000 — exceeds Int64 max (9.2 × 10^18)
Factorial is an ideal overflow stress test because:
- It produces predictable overflow thresholds (13 for Int32, 21 for Int64)
- It grows explosively — just 1 increment can jump an order of magnitude
- It tests whether the application uses BigInteger vs. Int32/Int64
The Test Matrix for Factorial Systems
| Input | Expected Int32 system | Expected Int64 system | Expected BigInteger system |
|---|---|---|---|
| 12 | 479,001,600 ✓ | 479,001,600 ✓ | 479,001,600 ✓ |
| 13 | OVERFLOW (error or wrap) | 6,227,020,800 ✓ | 6,227,020,800 ✓ |
| 20 | OVERFLOW | 2,432,902,008,176,640,000 ✓ | 2,432,902,008,176,640,000 ✓ |
| 21 | OVERFLOW | OVERFLOW (error or wrap) | 51,090,942,171,709,440,000 ✓ |
| 100 | OVERFLOW | OVERFLOW | huge correct number ✓ |
The BigInteger Safety Net
Some systems use Java's BigInteger or Python's arbitrary-precision integers to avoid overflow entirely. These are correct approaches for factorial calculations. Your test should confirm:
- BigInteger: all inputs produce correct results (no overflow for any reasonable input)
- Int32: inputs ≥ 13 produce overflow
- Int64: inputs ≥ 21 produce overflow
What "Overflow" Looks Like in Each Scenario
- Silent wrap-around: Result is a wrong number (often negative). No error shown.
- Application exception: Error page / 500 response. Tells you the system tried to compute and failed.
- Pre-validation rejection: The system correctly rejects n > 20 (or whatever its limit is) with a clear error message before computing. This is the ideal behavior.
Pro Tip: When testing factorial systems, test n = 12 and n = 13 together. If 12 gives the correct answer (479,001,600) and 13 gives a different wrong answer or error, you've precisely located the overflow boundary. This is far more informative than just testing n = 100 and getting an error.
Key Takeaways
- 13! exceeds Int32; 21! exceeds Int64
- Factorial is an ideal overflow stress test due to its explosive growth
- Test one below and one above each overflow threshold for precise diagnosis
- The ideal system: validate input range AND use appropriate big-number type