In shell scripting how to find factorial of a number?
#!/bin/bash
counter=$1 #first argument
factorial=1
while [ $counter -gt 0 ] #while counter > 0
do
factorial=$(( $factorial * $counter ))
counter=$(( $counter - 1 ))
done
echo $factorial
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.
Please use this script to find factorial in Bash,
#!/bin/bash
num=$1
fact=1
for((i=1; i<=$num; i++))
do
let fact=fact*i
done
echo "Factorial is $fact"
You can use:
seq -s "*" 1 10 | sed 's/*$//g' |bc
on a mac
echo 500 | dc -e '?[q]sQ[d1=Qd1-lFx*]dsFxp'
There are a number of instructive examples on Rosetta Code.
Here's one I found particularly useful:
function factorial {
typeset n=$1
(( n < 2 )) && echo 1 && return
echo $(( n * $(factorial $((n-1))) ))
}