Implementing a Simple Recursive Algorithm for Factorial Calculation
Learn how to implement a simple recursive algorithm to calculate the factorial of a given integer.
Introduction to Recursive Factorial Calculation
This tutorial will guide you through implementing a simple recursive algorithm to calculate the factorial of a given integer.
Step 1: Define the Problem and the Approach
We are given an integer and we need to calculate its factorial. We will use a recursive approach to solve this problem.
Step 2: Define the Base Case
We will define the base case for the recursion, which is when the input is 0 or 1. In this case, the factorial is 1.
if n == 0 or n == 1:
return 1
Step 3: Define the Recursive Case
We will define the recursive case, which is when the input is greater than 1. In this case, we will call the function recursively with the input decremented by 1 and multiply the result by the current input.
else:
return n * factorial(n - 1)
Step 4: Call the Function with the Input
Finally, we will call the function with the input and print the result.
print(factorial(5)) # Output: 120
Example Use Case
Here's an example use case:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120