In this lesson we will calculate the factorial of a number in Python using various methods.
First let’s give the definition.
In mathematics, the factorial of a natural number n is the product of positive integers less than or equal to this number and is denoted by n!
So for example 5! = 5 * 4 * 3 * 2 * 1 = 120
while by convention 0! = 1
Python Factorial
Let’s now create a program for calculating the factorial in Python.
We take as input n and set the variable f equal to 1, that is, the neutral element of the multiplication.
Then, with a for loop that has the index i that varies from a range of 1 to n + 1, we calculate the factorial by performing this operation f = f * i.
So if for example n is equal to 5 we will have these steps:
f = 1 * 1, f = 1 * 2, f = 2 * 3, f = 6 * 4, f = 24 * 5
In output we will therefore print 120.
A possible implementation of the algorithm can therefore be this:
n=int(input('Insert a number: '))
f=1
for i in range(1,n+1):
f*=i
print(n)
Recursive solution to the factorial
We can also find a recursive solution. Let’s first give the definition.
A function that calls itself is called recursive.
The recursive technique allows you to write elegant algorithms, but it is not always the most efficient solution. This is due to the fact that recursion is implemented with functions and the invocation of a function clearly has a significant cost.
We therefore define a function and inside we first check if n is equal to 0, returning the value 1. Otherwise we multiply n by the factorial of n-1.
We therefore propose the second solution to the computation of the factorial in Python which makes use of recursion.
n = int(input('Insert a number: '))
def fact_number(n):
if n == 0:
return 1
else:
return n * fact_number(n-1)
print('Factorial: ', fact_number(n))