Factorials with Python
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
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)
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.
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.