
Factorial program in Python helps to calculate the factorial of a number using the Python programming language. Nowadays, Python is one of the most widely used among developers worldwide due to its easy-to-learn and code syntax. It consists of an extensive set of libraries and frameworks to help you perform various operations effectively. Read the complete article to learn how to write a factorial program in Python.
| Factorial Program in Python |
| Read the user input number Fact = 1 i = 1 WHILE i< = number Fact = Fact * i i = i +1 END WHILE PRINT Fact |
| Factorial Program in Python: Recursive Algorithm |
| function factorial (n) : if n == 0 return 1 else: return n * factorial (n-1) |
| Factorial Program in Python: Recursive Algorithm |
| class Solution: def factorial (self, N): if(N==1): return N elif(N==0): return 1 return N*self.factorial(N-1) |
| Factorial Program in Python: Iterative Algorithm |
| function factorial (n): result = 1 for i from 2 to n: result *= i return result; |
| Factorial Program in Python: Iterative Algorithm |
| def factorial_iterative(n): if n < 0: return None # Factorial is not defined for negative numbers result = 1 for i in range(1, n + 1): result *= i return result |
| Difference between Recursive and Iterative Approach | |
| Recursive Approach | Iterative Approach |
| In recursive approach, function calls itself directly or indirectly. | In iterative approach, loops are used to repeatedly execute a set of statements. |
| It break down the problem into subproblem and then calculate the factorial. | It uses single loop to find the factorial minimizing the risk of stack overflow. |
| This approach is poor for large factorials as it can be time consuming and inefficient because of the repeated function calls. | The iterative approach is efficient for large factorials. |
| It consists of overhead caused by recursive function calls. | It do not consists of overhead of recursive function calls. |
| It uses more memory. | It uses less memory. |