In mathematics, a factorial of a positive integer ‘n’ is denoted by ‘n!’ and is calculated by multiplying all positive integers from 1 to ‘n.’ In simpler terms, it’s the product of ‘n’ and all the positive integers smaller than ‘n.’
For example:
- Factorial of 3 is 3! = 1 * 2 * 3 = 6.
- Factorial of 6 is 6! = 6 * 5 * 4 * 3 * 2 * 1, which equals 720.
It’s important to note that, by default, the factorial of 0 is defined as 1, and the factorial of a negative number is not defined in standard mathematics.
Mathematical Notation
In mathematical notation, a factorial is denoted by an exclamation mark ‘!’. The formula to calculate the factorial of ‘n’ is expressed as:
n! = n x (n-1) x (n-2) x (n-3) x ... x 1
Additionally, factorials can also be computed using Euler’s gamma function:
n! = γ(n+1) = \(∫_0^∞\) xn e-x dx
To find the factorial of a number in C, you can use various methods. Here are six different approaches to program this function:
- Factorial Program in C using For Loop
- Factorial Program in C using While Loop
- Factorial Program in C using Recursion
- Factorial Program in C using Ternary Operator
- Factorial Numbers in a Given Range
- Optimised Solution for Factorial of Range of Numbers
This method demonstrates how to calculate the factorial of a number using a for loop in C. Factorials are essential mathematical operations, and this approach provides a practical way to compute them.
Here is source code of the C program to print the factorial of a given number using for loop (iterative solution). The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to find the factorial of a given number using for loop. */ #include <stdio.h> void main() { // fact to store factorial of number N int fact = 1, n; // Take input printf("Enter the number: \n"); scanf("%d", &n); // Check validity of N if (n <= 0) fact = 1; // Loop N times and multiply all positive numbers else { for (int i = 1; i <= n; i++) { fact = fact * i; } } // Print the fact. printf("Factorial of %d = %5d\n", n, fact); }
1. Take a number and store it in ‘n’.
2. Check whether it is a valid number or not.
3. If not a valid number, print the message.
4. Else, run a for loop from 1 to N.
5. Take a variable ‘fact’ and store all the multiplication of N numbers in it.
6. Print the factorial value.
Example:
Let’s take an example with ‘n‘ as 6. First, we check if ‘n’ is less than or equal to 0, which it isn’t. We then run a for loop from 1 to 6, multiplying the numbers along the way and storing the result in ‘fact’. The final output is the factorial of 6, which is 720.
Time Complexity: O(N)
The program runs a for loop ‘N’ times to calculate the factorial is O(N).
Space Complexity: O(1)
Since we are not using constant space for computation, it’s space complexity is O(1).
Here is the runtime output of a C program to find the factorial of a number when the number entered by the user is “6”.
Enter the number: 6 Factorial of 6 = 720
In this method, we calculate the factorial of a number in C using a while loop. This approach provides an iterative solution to compute factorials efficiently.
Here is source code of the C program to print the factorial of a given number using while loop (iterative solution). The C program is successfully compiled and run on a Linux system. The program output is also shown below.
// c program to calculate factorial of a number using while loop #include <stdio.h> int main() { int num, i = 1; unsigned long long int factorial_of_num = 1; printf("Enter the number whose factorial you want to calculate: "); scanf("%d", &num); while (i <= num) { factorial_of_num *= i; i++; } printf("Factorial of %d is %llu ", num, factorial_of_num); return 0; }
1. The program initiates by prompting the user for a positive integer input, which is stored in the variable num.
2. It then uses a ‘while‘ loop to repeatedly calculate the factorial of the input number (‘num’) and keeps the result in ‘factorial_of_num‘. This is done by multiplying ‘factorial_of_num‘ with ‘i‘, which starts at 1 and increases until it reaches ‘num‘.
3. Once the ‘while‘ loop finishes, the program displays the calculated factorial with the message “Factorial of num is factorial_of_num“.
4. Finally, the program concludes by returning 0, indicating successful completion.
5. For example, if the user inputs 7, the program calculates 7! (7 factorial), which is 5040, and shows “Factorial of 7 is 5040”.
Complexity Analysis:
- Time Complexity: O(N) – The program uses a while loop that runs ‘N’ times, resulting in a linear time complexity.
- Space Complexity: O(1) – The program uses constant space for computation.
Here is the output of the program when we calculate the factorial of 7:
Enter the number whose factorial you want to calculate: 7 Factorial of 7 is: 5040
This method utilizes a recursive approach to calculate the factorial of a number N. It involves a recursive function factorial() that returns N! by multiplying N with (N-1)!.
Here is source code of the C program to print the factorial of a given number using recursive function. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * Factorial Program in C using Recursion */ #include <stdio.h> int factorial(int n) { // Base case for factorial function if (n == 0 || n == 1) { return 1; } else { return(n * factorial(n - 1)); } } int main() { // The number to calc n! int n; // variable to store ans int ans; printf("Enter a number to find it's Factorial: "); scanf("%d", &n); if (n < 0) { printf("Factorial of negative number not possible\n"); } else { // Calling factorial method ans = factorial(n); printf("The Factorial of %d is %d.\n", n, ans); } return 0; }
1. Take a number and store it in ‘n’.
2. Check whether it is a valid number or not.
3. If not a valid number, print the message.
4. Else, call recursive function.
5. Call same function for ‘n-1’ to get it’s factorial and multiply it with ‘n’ to get factorial of desired number.
6. Include the base case to stop the recursion.
7. Finally, print the answer.
Example:
Let’s take an example with N=10. The program computes N! as follows:
- It starts with N=10 and recursively calls 10 * factorial(9).
- This process continues until factorial(1) returns 1, and all the intermediate values are multiplied.
- The result is 10! = 3628800.
Time Complexity: O(N)
Since we are calling function for N times(N,N-1,N-2….3,2,1), time complexity is O(N).
Space Complexity: O(N)
In the context of recursion, a memory tree is created during execution, taking into account that
the space complexity of the tree is O(N).
Here is the runtime output of a C program to find the factorial of a number when the number entered by the user is “10”.
Enter a number to find it's Factorial: 10 The Factorial of 10 is 3628800
This method uses a concise one-liner solution by utilizing the ternary operator to call the recursive function for calculating the factorial.
Here is source code of the C program to print the factorial of a given number using ternary operator to call recursive function. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to find the factorial of a given number using ternary operator */ #include <stdio.h> int factorial(int n) { // Using ternary operators return ((n==0||n==1)?1:n*factorial(n-1)); } int main() { // The number to calc n! int n; // variable to store ans int ans; printf("Enter a number to find it's Factorial: "); scanf("%d", &n); if (n < 0) { printf("Factorial of negative number not possible\n"); } else { // Calling factorial method ans = factorial(n); printf("The Factorial of %d is %d.\n", n, ans); } return 0; }
Ternary Operator Explanation
The ternary operator (?:) works as follows:
(condition) ? (output if condition is true) : (output if condition is false)
In this method, the base condition is placed before ?. If the condition is true, it returns the base case; otherwise, it calls the recursive function.
Example:
Let’s take an example with N=6:
- It checks if N != 0 or N != 1, so it calls 6 * factorial(5).
- Then, with N=5, it again checks N != 0 or N != 1 and calls 5 * factorial(4).
- This process continues until 2 * factorial(1). Since factorial(1) returns 1, it computes the multiplication of all numbers and displays the result, which is 720.
Complexity Analysis
- Time Complexity: O(N) – The function is called ‘N’ times (N, N-1, N-2, …, 3, 2, 1), resulting in linear time complexity.
- Space Complexity: O(N) – Recursion creates a memory tree during execution, leading to a space complexity of O(N).
To calculate the factorial of a number, we enter “6” in this case:
Enter a number to find it's Factorial: 6 The Factorial of 6 is 720
In this method, we specify a start and end value for a range and then print the factorials for all the numbers within this range.
Here is source code of the C program to print the factorial numbers in a given range. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to find the factorial factorial numbers in a given range. */ #include<stdio.h> int main() { long fact=1; int start,end; printf("Enter the starting value of range: "); scanf("%d",&start); printf("Enter the ending value of range: "); scanf("%d",&end); printf("Factorial series of the given range is: "); for(int n=start;n<=end;n++) { // Calculating factorial for each number of range fact=1; for(int x=1;x<=n;x++) { fact=fact*x; } // Printing the output printf("%ld ",fact); } return 0; }
1. Take the start value and end value of range as input.
2. Loop for each value in the range.
3. Calculate the factorial of each value of the given range by iterating again for ‘N’ times.
Example:
Let’s consider the range with a start of 4 and an end of 8:
- Starting from N=4 and ending at N=8, it calculates the factorial for each value in the range.
- For N=4, it runs a loop from N=1 to N=4, multiplies all the numbers, stores the result, and prints the answer.
- This process continues for N=5, N=6, N=7, and N=8, printing all the factorial values, which are 24, 120, 720, 5040, and 40320.
Complexity Analysis
- Time Complexity: O(N2) – Due to two nested loops, the time complexity is O(N2).
- Space Complexity: O(1) – Constant space is used for computation, resulting in a space complexity of O(1).
To calculate the factorial of numbers within a given range, we enter the starting value as “4” and the ending value as “8”:
Enter the starting value of range: 4 Enter the ending value of range: 8 Factorial series of the given range is: 24 120 720 5040 40320
This method focuses on optimizing the calculation of factorials within a given range. Instead of iteratively computing factorials for each number in the range, it precomputes the multiplication of numbers smaller than the starting value of the range. Then, it efficiently computes the factorials for the entire range.
Here is source code of the C program to print the factorial numbers in a given range using optimised approach. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to find the factorial factorial numbers in a given range. */ #include<stdio.h> int main() { long fact=1; int start,end; printf("Enter the starting value of range "); scanf("%d",&start); printf("Enter the ending value of range "); scanf("%d",&end); printf("Factorial series of the given range is: "); int a=1; // Preconpute multiplication of numbers smaller than start for(int i=1;i<start;i++) { a=a*i; } // Iterate from start to end for(int n=start;n<=end;n++) { // Compute factorial fact=a*n; // Update the precomputed value a=a*n; printf("%ld ",fact); } return 0; }
1. Take the start value and end value of range as input.
2. Precompute the multiplication of all the numbers smaller than start value and store it in ‘a’.
3. Iterate from start to end.
4. Multiply each number from precomputed value and print the answer.
5. After that update the precalculated value by recently calculated value.
Example:
Let’s consider the range with a start of 4 and an end of 8:
- First, it runs a loop from N=1 to N=3 to calculate the multiplication of numbers and stores it in ‘a’.
- Then, it loops from N=4 to N=8.
- For N=4, it multiplies ‘a’ with 4 and prints the answer. It updates ‘a’ with a * 4.
- It continues this process for N=5, N=6, N=7, and N=8, printing all the factorial values, which are 24, 120, 720, 5040, and 40320.
Complexity Analysis:
- Time Complexity: O(N) – This method implements two loops, but they are not nested. Therefore, the time complexity is O(N).
- Space Complexity: O(1) – It uses constant space for computation, resulting in a space complexity of O(1).
To calculate the factorial of numbers within a given range, enter the starting value as “4” and the ending value as “8”:
Enter the starting value of range: 4 Enter the ending value of range: 8 Factorial series of the given range is: 24 120 720 5040 40320
To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.
- Check Computer Science Books
- Practice BCA MCQs
- Check C Books
- Apply for C Internship
- Watch Advanced C Programming Videos