Efficiently print factorial series in a given range

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

 

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

 


 

1. Iterative solution

The iterative version uses a for loop to calculate the product of all positive integers less than equal to n. Naive solution calculates factorial again and again for every number in the given range while efficient solution uses the previous results to calculate factorial of next number.

Naive

Download   Run Code

Efficient

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

 

2. Recursive solution

Factorial of a number can be recursively defined as –


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

Naive

Download   Run Code

Efficient

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz