Recursively find the factorial of a natural number.
Published in
1 min readDec 18, 2019
Recursion:
“Recursion is a process in which a problem is defined in terms of itself”.
The problem is solved by repetitively breaking it into a smaller problem which is similar in nature to the original problem.
To compute factorial using recursion the below code helps:
def factorial(n):
if(n==1 or n==0):
return 1
else:
return n*factorial(n-1)
num=int(input())
print(factorial(num))
Here assume num is 6
factorial(6) is called and 6*factorial(5) is returned
6*factorial(5) becomes 6*5*factorial(4)
6*5*factorial(4) becomes 6*5*4*factorial(3)
6*5*4*factorial(3) becomes 6*5*4*3*factorial(2)
6*5*4*3*factorial(2) becomes 6*5*4*3*2*factorial(1)
Finally, for factorial(1) the value 1 is returned
So,
6*5*4*3*2*1=720
The value 720 is printed on the console.