Write a recursive C/C++, Java, and Python program to calculate the factorial of a given non-negative number.

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. There are n! different ways to arrange n distinct objects into a sequence. For example,

The value of 5! is 120 as
5! = 1 × 2 × 3 × 4 × 5 = 120
 
The value of 0! is 1

Practice this problem

We can recursively define the problem as:

n! = | n * factorial(n – 1)        if n > 0
     | 1                           if n = 0

For example,

0! = 1! = 1
2! = (1) × 2 = 1! x 2 = 2
3! = (1 × 2) x 3 = 2! x 3 = 6
4! = (1 × 2 × 3) × 4 = 3! x 4 = 24
5! = (1 × 2 × 3 × 4) × 5 = 4! x 5 = 120
6! = (1 × 2 × 3 × 4 × 5) x 6 = 5! x 6 = 720

This is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The Factorial of 5 is 120

Java


Download  Run Code

Output:

The Factorial of 5 is 120

Python


Download  Run Code

Output:

The Factorial of 5 is 120

The time complexity of the above solution is O(n), and the auxiliary space used by the program is O(n) for the call stack.

 
We can also write the above recursive program in a single line, as shown below:

C


Download  Run Code

Output:

The Factorial of 6 is 720

Java


Download  Run Code

Output:

The Factorial of 6 is 720

Python


Download  Run Code

Output:

The Factorial of 6 is 720

 
Also see:

Iterative program to find factorial of a number

 
Exercise: Efficiently print factorial series in a given range.