Factorial of any number N using recursion
Recursion is a property of function where it can call itself. Recursion is only available to a few programming languages like C, C++, and Python.
Factorial of any number n is equal to its multiplication of 1x2x3 upto n-1x n. There are two methods to find out factorial of n. 1
- Using Looping method
- Using recursion
1. Factorial of Number N using Looping
Looping means repeatation-Python support only two type of loops- while loop and for loop.
# program to find out factorial of any number n using looping method #made by : rakesh kumar n = int(input('Enter any number n: ')) fact = 1 for i in range(1, n+1): fact *= i print('Factorial of {} is {}'.format(n, fact))
Other programs written using for loops are as follows
- Character rhombus using for loop
- Character Parallelogram using loop
- Number tree using for loop
- Number triangle using for loop
Factorial of any number N using recursion
Since in this case we are bound to call our user-defined function in order to find out the factorial of our input number N. Here is the code for computing factorial of integer number N.
def factorial(n): if n==1: return 1 else: return n*(factorial(n-1)) #function call n = int(input("Enter any number ")) result = factorial(n) print("factorial of {} is {} ".format(n,result))
The output of the above program is as follows
rakesh@folio MINGW64 /e/python (master) $ python -u "e:\python\Loops\factorial.py" Enter any number n: 4 Factorial of 4 is 24
Recursion is an integral part of dynamic programming. This question is a part of the practical assignments of class 12 python students. You can download a sample list of practical assignments for class 12 computer science students. here.