Factorial – Solution & Complexity
Solution Walkthrough
Step 1: Understand the Definition
- Factorial means multiplying all positive integers from
1throughn. - By definition,
0!equals1. - The input is non-negative, so we do not need to handle negative numbers.
- Factorial means multiplying all positive integers from
Step 2: Recursive Idea
- Factorial has a direct recursive definition:
n! = n * (n - 1)!. - The base case is
0! = 1or1! = 1. - This works, but an iterative loop avoids recursion depth concerns.
- Factorial has a direct recursive definition:
Step 3: Iterative Accumulation
- Start with
result = 1. - Multiply by each number from
2throughn. - If
nis0or1, the loop does not run and the answer remains1.
- Start with
Step 4: Build the Loop
- Use
range(2, n + 1)so the final multipliernis included. - Update the running product each iteration.
- Return the product after all factors have been applied.
- Use
Step 5: Final Solution and Complexity
- The solution directly follows the mathematical definition.
- Time complexity is O(n).
- Space complexity is O(1) because it uses one accumulator.