Python Factorial | Factorial Formula Vs. Recursion Method

Python-Factorial-Factorial-Formula-Vs.-Recursion-Method
Credit: Canva

Overview

In this article, I’ll start with Python Factorial | Factorial Formula Vs. Recursion Method but before moving ahead, I’ll discuss the Prerequisites you need to know to calculate Python Factorial.

What’s Next?

In this project on how to Calculate Factorial in Python, I’ll walk you through 2 ways to find the Python Factorial. First is Calculate Factorial using the default formula and second Calculate Factorial in Python using Recursion Method.

Table of Contents

Watch Video Explanation

Prerequisites you need to know:

f string – The letter f is prefixed to use Python f string, which is used to insert your string (or value) in the statement by using a placeholder i.e., square brackets {}.

def functiondef is a reserved keyword, used to create customized Python functions. A custom function name is being written just after the def keyword. Passing the parameter name is optional.

Syntax:

				
					def function_name(parameters):
# Code block
return result  # (optional) returns a value to the caller
				
			

Explanation:

function_name: Custom function name, used to call it later.

parameters: Optional inputs that the function takes to perform its task.

return: An optional statement to return a result from the function. If no return statement is given, the function will return None by default.

For more details: Introduction to Python Def Function

Conditional statement – Python conditional statement is used to define the conditions in Python. It is defined by the code of block – if..elif…else… As a result, conditional statements return true or false based on the given conditions.

Use cases:

if: Tests a condition. If true, executes the block of code inside.

elif: Short for “else if,” allows you to check multiple conditions if the initial if statement is false.

else: Executes a block of code if all preceding conditions are false.

Syntax:

				
					if condition1:
    # Code to execute if condition1 is true
elif condition2:
    # Code to execute if condition1 is false and condition2 is true
else:
    # Code to execute if all conditions are false
				
			

For more details: Python Conditional Statement

Recursive case – Recursive case is the part where a function calls itself to solve a smaller instance of the original problem. In other words, recursive functions break down the problem into small problems, eventually leading to the base case, where recursion stops.

Explanation:

Calls Itself: The recursive case involves a function calling itself with modified arguments.

Progress Toward Base Case: Each recursive call reduces the size of the problem to reach to the base case.

Combines Results: The solutions from the smaller problems are combined to solve the original problem.

What is Factorial?

A Factorial is the product of all natural numbers from n to 1. Where n is the number whose factorial is being calculated. Its sign is defined by an exclamation mark (!).

Example:

n! = 4

4! = 4*3*2*1 = 24

The formula of the Factorial:

n! = n*(n-1)!

Factorial using default Formula

				
					n = 2 #factorial number
formula = n*(n-1) #factorial formula
print(f"The factorial of {n}! is {formula}")
				
			

Explanation:

The variable n is assigned the value 2, whose factorial is being calculated.

Next, define the Factorial formula i.e., formula = n * (n – 1).

Now, we have an expression,

formula=2×(2−1)=2×1=2

Note: This method works only with a factorial of 2. It will not work with a number greater than 2 because it doesn’t include further multiplication beyond n-1.

Next, used the Python print() function to display the factorial. Here I used an f-string for formatting the statement i.e., inserting the customized value into the statement.

Finally, we get the output: The factorial of 2! is 2.

Factorial using Recursive case

				
					def factorial(n):
    if n == 0:  #base case
        return 1
    else:        #recursive condition
        return n*factorial(n-1)

number = 4
result = factorial(number)
print(f"The factorial of {number}! is {result}")
				
			

Explanation:

The program starts with a function named factorial is defined to calculate the factorial of a number n using recursion.

Base Case:

The first case is when n = 0.

It returns 1 because 0! = 1. In this condition, recursion stops.

Recursion Case:

The second case is when n > 0.

formula = n!=n×(n−1)!

This is the part where the function calls itself with n−1 moving closer to the base case of n=0.

Now, the function is being called and the value 4 (‘number’ – variable) is passed to the parameter of the function i.e., n.

Step-by-Step Execution:

The function starts with n=4

factorial(4)=4×factorial(3)

Now, calculate factorial(3):

factorial(3)=3×factorial(2)

Now, calculate factorial(2):

factorial(2)=2×factorial(1)

Finally, calculate factorial(1):

factorial(1)=1×factorial(1)

The base case is reached at factorial(0 ) = 1, and recursion stops.

Recursive calls are multiplied as follows:

factorial(4) = 4x3x2x1 = 24.

Recent Articles