Introduction
Factorial means:
- multiplying all numbers
- from 1 to n
Factorial of:
- 5 = 5 × 4 × 3 × 2 × 1
Example:
5! = 120 Explanation:
5 × 4 × 3 × 2 × 1= 120
This problem is one of the most important applications of:
Recursion Constraints
0 <= n <= 20 Approach 1 : Iterative Solution
Explanations:
Explanation:
The idea is:
- start from 1
- multiply numbers one by one
Steps:
- Initialize answer as 1.
- Traverse from 1 to n.
- Multiply values.
- Print result.
This approach:
- avoids recursion
- is beginner friendly
Dry Run
n = 5
result = 1
1 × 2 = 2
2 × 3 = 6
6 × 4 = 2424 × 5 = 120
Practice :
Complexity Analysis :
Time Complexity:- O(n)
Explanation :
Loop runs n times.
Space Complexity:- O(1) Explanation :No extra space is used.
Approach 2 : Recursive Solution
Explanations:
Explanation:
This is the most important recursion-based solution.
The idea is:
- factorial(n)
- equals n × factorial(n-1)
Base Case:
- factorial(0) = 1
Recursive Case:
- factorial(n) = n × factorial(n-1)
Dry Run
factorial(5)
5 × factorial(4)
5 × 4 × factorial(3)
5 × 4 × 3 × factorial(2)
5 × 4 × 3 × 2 × factorial(1)
5 × 4 × 3 × 2 × 1 = 120
Practice :
Complexity Analysis
Time Complexity:- O(n)
Explanation :
Recursive calls run n times.
Space Complexity:- O(n)
Explanation :
Recursion stack is used.
Why This Problem is Important
Time Complexity:- O(n) Explanation :
Recursive calls run n times.
Space Complexity:- O(n) Explanation :
Recursion stack is used.
Why This Problem is Important