Program to find factorial of a given number | Iterative & Recursive

Write a C/C++ and java program to calculate factorial of a given positive 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!.


For example,


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

The value of 0! is 1

The most basic use of factorial operation is n distinct objects can be arranged into a sequence in n! ways.

 


 

1. Iterative solution

The iterative version simply use a for or a while loop to calculate the product of all positive integers less than equal to n. Since the factorial of a number can be huge, the data type of factorial variable is declared as unsigned long.

C

Download   Run Code

Output:

The Factorial of 5 is 120

Java

Download   Run Code

Output:

The Factorial of 5 is 120

The time complexity of above solution is O(n) and uses constant space.

 


 

2. Recursive solution

We can easily convert above iterative program to recursive one. The problem can be recursively defined as –


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

For example,


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

C

Download   Run Code

Output:

The Factorial of 5 is 120

Java

Download   Run Code

Output:

The Factorial of 5 is 120

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

We can also write above recursive program in a single line as shown below –

 
Exercise: Efficiently print factorial series in a given range.

 
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