DSA problem
Factorial of a Number
Given an integer N, compute its factorial, defined as N! = N * (N-1) * (N-2) * ... * 1, with 0! = 1 by convention.
Factorials underpin permutations, combinations, and probability. Iteratively, you simply multiply every integer from 1 to N; recursively, N! = N * (N-1)! with base case 0! = 1. Either way the cost is O(N).
An important practical concern is overflow: factorials grow extremely fast. 20! is already 2,432,902,008,176,640,000, which overflows a 32-bit integer, so use a 64-bit type such as long (or arbitrary-precision integers) for larger inputs.
Examples
Example 1
Input:
N = 5Output:
120Explanation: 5! = 5 x 4 x 3 x 2 x 1 = 120.
Constraints
- 0 <= N <= 20
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.