Tutorialspoint
Problem
Solution
Submissions

Factorial of a Number .

Certification: Basic Level Accuracy: 58.82% Submissions: 17 Points: 10

Write a C# 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: n = 5
  • Output: 120
  • Explanation:
    • Step 1: Check if n is 0 or 1. If so, return 1 (base case).
    • Step 2: For n = 5, recursively calculate 5 × factorial(4).
    • Step 3: For factorial(4), recursively calculate 4 × factorial(3).
    • Step 4: For factorial(3), recursively calculate 3 × factorial(2).
    • Step 5: For factorial(2), recursively calculate 2 × factorial(1).
    • Step 6: For factorial(1), return 1 (base case).
    • Step 7: Return 5 × 4 × 3 × 2 × 1 = 120.
Example 2
  • Input: n = 0
  • Output: 1
  • Explanation:
    • Step 1: Check if n is 0 or 1. Since n = 0, return 1 (base case).
    • Step 2: By mathematical definition, factorial of 0 is 1.
Constraints
  • 0 ≤ n ≤ 12 (to prevent integer overflow)
  • Time Complexity: O(n) (Recursive calls up to n)
  • Space Complexity: O(n) (Recursive call stack)
ArraysRecursionTutorialspointAdobe
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

Submitted Code :