Factorial of a number

Factorial of a number

Welcome Learners!. In this post “Factorial of a number”, you will be learning about what is a factorial. And how to compute it using iterative method as well as recursive approach. You can also refer to my posts Java – A robust Language, Queue – Data Structure.

Factorial of a number

Factorial of any value is nothing but multiplication of all the numbers up to the given value. Exclamation symbol ‘!’ denotes factorial. for example 0! is zero factorial. The value of zero factorial (0!) is 1 (One).
few more examples:
1!= 1
2!= 1*2 = 2
3!= 1*2*3 = 6
4!= 1*2*3*4= 24
5!= 1*2*3*4*5 = 120
6!= 1*2*3*4*5*6 = 720
.
.
.
.
and so on

Approach

The approach to compute factorial of a value is quite simple. Multiply every no. from 1 to the given value. This is just as simple as that.

It can be implemented in two ways. One is recursive and the other is iterative.

Factorial of a number – Iterative implementation

Iterative implementation is a top down implementation. You need take a variable for storing factorial. Initialize the variable to 1. Then you need to iterate using for or while loop up to the given number and multiply each no. with the result variable.

Code

def fact(n):
f = 1
for i in range(2,n+1):
f = f * i
return f

Recursive implementation

Recursive implementation consists of several calls of same function. Number of recursive calls depends upon the given number. You can implement the recursive approach as simple as iterative approach. All you need to do is a recursive call for the factorial of a previous value. And then multiple by current value.

For example, if you want to compute 5!, all you need to do is get the value of four factorial. And then multiply it by 5.
5! = 5 * (4!) = 5 * 24 = 120

code

def fact(n):
if n==0 or n==1:
return 1
return n * fact(n-1)

Practice