Wednesday, July 8, 2026
HomeLanguagesPython program to find the factorial of a number using recursion

Python program to find the factorial of a number using recursion

A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than or equal to n.

n! = n*(n-1)*(n-2)*(n-3)*....*1

For example:

5! = 5*4*3*2*1 = 120

In this article, we are going to calculate the factorial of a number using recursion.

Examples:

Input: 5
Output: 120

Input: 6
Output: 720

Implementation:

If fact(5) is called, it will call fact(4), fact(3), fact(2) and fact(1). So it means keeps calling itself by reducing value by one till it reaches 1.

Python3




# Python 3 program to find 
# factorial of given number
def factorial(n):
     
    # Checking the number
    # is 1 or 0 then
    # return 1
    # other wise return
    # factorial
    if (n==1 or n==0):
         
        return 1
     
    else:
         
        return (n * factorial(n - 1))
 
# Driver Code
num = 5;
print("number : ",num)
print("Factorial : ",factorial(num))


Output

number :  5
Factorial :  120

Time complexity: O(n)

Space complexity: O(n)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32519 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12016 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12111 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7263 POSTS0 COMMENTS
Thapelo Manthata
6978 POSTS0 COMMENTS
Umr Jansen
6968 POSTS0 COMMENTS