 GeeksforGeeks App
Open App Browser
Continue

# Shell Program to Calculate the Factorial of a Number

Here we are going to see to calculate the factorial of a number. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n.

For example factorial of 5 is 5*4*3*2*1 which is 120. ### Method 1: Using Recursive

Factorial can be calculated using the following recursive formula. Below is  implementation of factorial:

#!/bin/bash
# Recursive factorial function

factorial()
{
product=$1 # Defining a function to calculate factorial using recursion if((product <= 2)); then echo$product
else
f=$((product -1)) # Recursive call f=$(factorial $f) f=$((f*product))
echo $f fi } # main program # reading the input from user echo "Enter the number:" read num # defining a special case for 0! = 1 if((num == 0)); then echo 1 else #calling the function factorial$num
fi

Output:

Enter the number
5
120

Enter the number
3
24

Enter the number
6
720

### Method 2: Using for loop

Approach:

• Get a number
• Use for loop to compute the factorial by using the below formula
• fact(n) = n * n-1 * n-2 * …
• Display the result.

Below is the Implementation using for loop:

# shell script for factorial of a number
# factorial using for loop

echo "Enter a number"

fact=1

for((i=2;i<=num;i++))
{
fact=$((fact * i)) } echo$fact

Output:

Enter a number
5
120

Enter a number
7
5040

Enter a number
4
24

### Method 3: using do-while loop

• Get a number
• Use do-while loop to compute the factorial by using the below formula
• fact(n) = n * n-1 * n-2 * .. 1
• Display the result.

Below is the Implementation using a while loop.

# shell script for factorial of a number
# factorial using while loop

echo "Enter a number"

fact=1

# -gt is used for '>' Greater than sign
while [ $num -gt 1 ] do fact=$((fact * num))
num=$((num - 1)) done # Printing the value of the factorial echo$fact            

Output:

Enter a number
10
3628800

Enter a number
2
2

Enter a number
9
362880
My Personal Notes arrow_drop_up