Find Factorial Of A Number in Bash Script
Q. Write a bash script to find the factorial of number?
What is a factorial number? A factorial number of any given number is the multiplication of all positive integers less than or equal to a given positive integer.
The factorial denoted with ! symbol. For example. The factorial of 5, 8 and 1 will be:
- 5! = 4 × 3 × 2 × 1 = 24
- 8! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
- 1! = 1
Example
A shell script to calculate the factorial of input number using for loop.
1 2 3 4 5 6 7 8 9 10 11 12 | #!/bin/bash # A shell script to find the factorial of a number read -p "Enter a number" num fact=1 for((i=2;i<=num;i++)) { fact=$((fact*i)) } echo $fact |
Another Example
A shell script to calculate the factorial of input number using while loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/bin/bash # A shell script to find the factorial of a number read -p "Enter a number" num fact=1 while [ $num -gt 1 ] do fact=$((fact*num)) num=$((num-1)) done echo $fact |