In shell scripting how to find factorial of a number?
I almost completely agree with Vitalii Fedorenko, I would just like paxdiablo suggests use bc
, here's the code from Vitalii Fedorenko but modified to use bc
.
#!/bin/bash
counter=$1
output=1
while [ $counter -gt 1 ] #while counter > 1 (x*1=x)
do
output=$(echo "$output * $counter" | bc)
counter=$(($counter - 1))
done
#remove newlines and '\' from output
output=$(echo "$output" | tr -d '\' | tr -d '\n')
echo "$output"
exit
This method is better because bc
allows you to use strings, instead of integers, making it possible for you to calculate much bigger numbers.
I apologize if I haven't used tr
correctly, I am not very familiar with it.