Bash Script to Find Factorial Using Recursion
factorial() { if [ $1 -le 1 ]; then echo 1; else local temp=$(( $1 - 1 )); local result=$(factorial $temp); echo $(( $1 * result )) ; fi } and calling it with a number.Examples
How to Think About It
Algorithm
Code
#!/bin/bash
factorial() {
if [ $1 -le 1 ]; then
echo 1
else
local temp=$(( $1 - 1 ))
local result=$(factorial $temp)
echo $(( $1 * result ))
fi
}
read -p "Enter a number: " num
fact=$(factorial $num)
echo "Factorial of $num is $fact"Dry Run
Let's trace factorial(3) through the code
Call factorial(3)
3 > 1, so call factorial(2)
Call factorial(2)
2 > 1, so call factorial(1)
Call factorial(1)
1 <= 1, return 1
Return from factorial(2)
2 * 1 = 2
Return from factorial(3)
3 * 2 = 6
| Call | Returned Value |
|---|---|
| factorial(1) | 1 |
| factorial(2) | 2 |
| factorial(3) | 6 |
Why This Works
Step 1: Base Case
The function stops calling itself when the input is 1 or less using if [ $1 -le 1 ], returning 1 to avoid infinite recursion.
Step 2: Recursive Call
For inputs greater than 1, the function calls itself with $1 - 1 to break down the problem into smaller parts.
Step 3: Multiplying Results
Each recursive call returns a factorial value that is multiplied by the current number to build the final factorial.
Alternative Approaches
#!/bin/bash read -p "Enter a number: " num fact=1 for (( i=2; i<=num; i++ )) do fact=$(( fact * i )) done echo "Factorial of $num is $fact"
#!/bin/bash
factorial() {
if [ $1 -le 1 ]; then
echo 1
else
echo "$1 * $(factorial $(( $1 - 1 )))" | bc
fi
}
read -p "Enter a number: " num
fact=$(factorial $num)
echo "Factorial of $num is $fact"Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per number down to 1, so it runs in linear time proportional to the input number.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used grows linearly with the input.
Which Approach is Fastest?
The iterative approach is faster and uses less memory because it avoids recursive call overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Learning recursion, small inputs |
| Iterative | O(n) | O(1) | Performance and large inputs |
| bc Calculator | O(n) | O(n) | Handling very large numbers |