Write an iterative program to print factorial series in a given range efficiently.

The factorial n! of a non-negative integer n is the product of all positive integers less than or equal to n. For example, if the given range is [5, 10].

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

Practice this problem

The iterative version uses a for loop to calculate the product of all positive integers less than equal to n. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
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 again and again for every number in the given range. An efficient solution is to use the previous results to calculate the factorial of the next number, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Find all factorial numbers less than or equal to n