Factorials with Python

Sandun Dayananda
2 min readSep 2, 2022

--

We can define an algorithm as a sequence of well-defined instructions that solves a problem or performs a computation with a finite number of steps.

Main components of an algorithm

•sequence (a group of instructions to be performed in order)

•selection (if, elif and else)

iteration (for, while)

•abstraction (functions and methods)

Following is the simple definition of factorial of n

how factorial should work
How factorial should work

There are two main approaches to factorial finding algorithms. Iterative approach and recursive approach.

Iterative approach:

Following is the code for calculating the factorial of n. You can see here for loop is used. You can think that the same calculation is used again and again in order to get the final output. That is iteration. (Here you should be aware that i in range (1,4) means i value goes from 1 to 3 only. It does not include 4)

Iterative function to calculate the factorial of n
Iterative function to calculate the factorial of n

Recursive approach:

Recursion means a defined function can call itself. We know one python function can call another python function. Likewise, one function can call itself. Then it is called a recursive function.

Recursive function to calculate the factorial of n
Recursive function to calculate the factorial of n

Here, as you can understand, recursion ends when the number reduces to 1. This is called the base condition.

When you write a recursive function, it must have a base condition that stops the recursion, or else the function calls itself infinitely. Then that uses excess amounts of memory or processor power.

The Python interpreter limits the number of recursions to 1000 to help avoid infinite recursions. When this limit is exceeded, it outputs a recursion error.

--

--

Sandun Dayananda
Sandun Dayananda

Written by Sandun Dayananda

Big Data Engineer with passion for Machine Learning and DevOps | MSc Industrial Analytics at Uppsala University

No responses yet