Iterative program to find factorial of a number
Write an iterative C/C++ and java program to find 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!. Factorial is mainly used to calculate the total number of ways in which n distinct objects can be arranged into a sequence.
For example,
5! = 1 × 2 × 3 × 4 × 5 = 120
(5 distinct objects can be arranged into a sequence in 120 ways).
The value of 0! is 1
The iterative version uses a 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.
The implementation can be seen below in C, Java, and Python:
C
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> // Iterative function to find factorial of a number using a for-loop unsigned long factorial(int n) { unsigned long fact = 1; for (int i = 1; i <= n; i++) { fact = fact * i; } return fact; } int main() { int n = 5; printf("The Factorial of %d is %lu", n, factorial(n)); return 0; } |
Output:
The Factorial of 5 is 120
Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Main { // Recursive function to find factorial of a number public static long factorial(int n) { long fact = 1; for (int i = 1; i <= n; i++) { fact = fact * i; } return fact; } public static void main(String[] args) { int n = 5; System.out.println("The Factorial of " + n + " is " + factorial(n)); } } |
Output:
The Factorial of 5 is 120
Python
The time complexity of the above solution is O(n) and requires constant space.
Also See:
Exercise: Efficiently print factorial series in a given range
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)