![]() |
VOOZH | about |
Given a non-negative integers n, compute the factorial of the given number. Factorial of n is defined as n * (n -1) * (n - 2) * ... * 1. For n = 0, the factorial is defined as 1.
Examples:
Input: n = 5
Output: 120
Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120Input: n = 4
Output: 24
Explanation: 4! = 4 * 3 * 2 * 1 = 24
Input: n = 0
Output: 1Input: n = 1
Output: 1
Table of Content
Factorial is computed by multiplying all integers from 1 to n using a loop. We initialize a variable ans as 1 and update it in each iteration by multiplying with the current number. This approach avoids recursion and uses constant extra space.
Step-by-step execution:
For n = 4
Final factorial = 24
120
Factorial is defined recursively as n! = n × (n - 1)!. We define a base case where if n equals 0 or 1, the function returns 1. Otherwise, the function calls itself with n minus 1, breaking the problem into smaller subproblems until reaching the base case.
120