ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Factorial Calculation with Recursion

Python

Goal -- WPM

Ready
Exercise Algorithm Area
1def factorial_recursive(n):
2"""Calculates the factorial of a non-negative integer recursively.
3
4Args:
5n: A non-negative integer.
6
7Returns:
8The factorial of n.
9"""
10if not isinstance(n, int) or n < 0:
11raise ValueError("Input must be a non-negative integer.")
12
13# Base case: factorial of 0 is 1
14if n == 0:
15return 1
16# Recursive step: n! = n * (n-1)!
17else:
18return n * factorial_recursive(n - 1)
Algorithm description viewbox

Factorial Calculation with Recursion

Algorithm description:

This function computes the factorial of a non-negative integer using recursion. The factorial of a number `n` (denoted as `n!`) is the product of all positive integers less than or equal to `n`. It's widely used in combinatorics, probability, and in defining other mathematical functions.

Algorithm explanation:

The factorial function is defined recursively: `n! = n * (n-1)!` for `n > 0`, and `0! = 1`. The recursive implementation directly mirrors this definition. The base case is when `n` is 0, where the function returns 1. For any `n > 0`, it returns `n` multiplied by the result of calling itself with `n-1`. This process continues until the base case is reached. The time complexity is O(n) because each number from `n` down to 1 is processed once. The space complexity is also O(n) due to the call stack depth. Input validation ensures `n` is a non-negative integer.

Pseudocode:

1. Define a function `factorial_recursive(n)`.
2. Validate that `n` is a non-negative integer; raise an error otherwise.
3. If `n` is 0, return 1 (base case).
4. Otherwise, return `n` multiplied by the result of calling `factorial_recursive(n - 1)` (recursive step).