Tutorialspoint
Problem
Solution
Submissions

Factorial of a Number

Certification: Basic Level Accuracy: 80% Submissions: 10 Points: 5

Write a C++ function to find the factorial of a given non-negative integer using recursion.

Example 1
  • Input: number = 5
  • Output: 120
  • Explanation:
    • Step 1: Calculate 5! = 5 × 4 × 3 × 2 × 1.
    • Step 2: Recursively calculate 5 × 4!.
    • Step 3: Continue recursion until reaching the base case (0! = 1).
    • Step 4: Return the final result 120.
Example 2
  • Input: number = 0
  • Output: 1
  • Explanation:
    • Step 1: By definition, 0! = 1.
    • Step 2: This is the base case of the recursion.
    • Step 3: Return 1 immediately.
Constraints
  • 0 ≤ number ≤ 20
  • Time Complexity: O(n)
  • Space Complexity: O(n) due to recursion stack
NumberRecursionMicrosoftCognizant
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

  • Use recursion to calculate the factorial.
  • Handle the base case where the number is 0 or 1.
  • Ensure the function works for the upper limit of the constraint.

Steps to solve by this approach:

 Step 1: Define a recursive function factorial that takes an integer number.
 Step 2: Establish the base case: if number is 0 or 1, return 1.
 Step 3: For other cases, return number multiplied by factorial of (number-1).
 Step 4: The recursion will continue until it reaches the base case.
 Step 5: In main, call factorial with a value and print the result.

Submitted Code :