Write a recursive program to find all factorial numbers less than or equal to n.

The factorial n! of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of number 5 is 120, and the factorial of number 6 is 720, and so on…

 
The factorial of a number can be recursively defined as:

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

Practice this problem

A simple solution is to call the factorial function for every number less than or equal to n using the above recurrence. This is demonstrated below in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 6
The factorial of 4 is 24
The factorial of 5 is 120
The factorial of 6 is 720
The factorial of 7 is 5040
The factorial of 8 is 40320
The factorial of 9 is 362880
The factorial of 10 is 3628800

 
The above solution calculates the factorial function repeatedly for each number less than or equal to n. An efficient solution is to call the factorial function only once for a number n and calculate the factorial of all numbers less than n in the same function call, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 6
The factorial of 4 is 24
The factorial of 5 is 120
The factorial of 6 is 720
The factorial of 7 is 5040
The factorial of 8 is 40320
The factorial of 9 is 362880
The factorial of 10 is 3628800