Tutorialspoint
Problem
Solution
Submissions

Recursive Function to Compute Factorial

Certification: Intermediate Level Accuracy: 50% Submissions: 2 Points: 10

Write a Python function that calculates the factorial of a given number using recursion. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.

Example 1
  • Input: 5
  • Output: 120
  • Explanation:
    • Step 1: Take the input number 5.
    • Step 2: Calculate the factorial: 5 × 4 × 3 × 2 × 1 = 120.
    • Step 3: Return 120 as the result.
Example 2
  • Input: 0
  • Output: 1
  • Explanation:
    • Step 1: Take the input number 0.
    • Step 2: The factorial of 0 is defined as 1.
    • Step 3: Return 1 as the result.
Constraints
  • 0 ≤ n ≤ 998 (Python recursion limit may be reached for larger values)
  • Return the factorial of the input number
  • Time Complexity: O(n), where n is the input number
  • Space Complexity: O(n) due to the recursion stack
ArraysRecursionTutorialspointWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Base case: if n is 0 or 1, return 1
  • Recursive case: return n * factorial(n-1)
  • Consider using memoization for optimization
  • Handle edge case for negative numbers

Steps to solve by this approach:

 Step 1: Define the base cases for factorial calculation (0! = 1 and 1! = 1).
 Step 2: Check if n equals 0 or 1, and return 1 if true.
 Step 3: For n > 1, use the recursive formula: n! = n × (n-1)!
 Step 4: Make a recursive call to factorial(n-1).
 Step 5: Multiply n with the result of factorial(n-1).
 Step 6: Return the product as the factorial of n.
 Step 7: Example: factorial(5) = 5 × 4! = 5 × 24 = 120.

Submitted Code :