I want to do a function that will return the factorial of a number in bash
Here\'s the current code that doesn\'t work, can anyone tell me what\'s wrong and how to c
#!/bin/bash
function factorial()
{
if (( $1 < 2 ))
then
echo 1
else
echo $(( $1 * $(factorial $(( $1 - 1 ))) ))
fi
}
This will work better.
(It works up to 25, anyway, which should be enough to prove the point about recursion.)
For higher numbers, bc would be the tool to use, making the ninth line above:
echo "$1 * $(factorial $(( $1 - 1 )))" | bc
but you have to be a bit careful with bc --
$ factorial 260
38301958608361692351174979856044918752795567523090969601913008174806\
51475135399533485285838275429773913773383359294010103333339344249624\
06009974551133984962615380298039823284896547262282019684886083204957\
95233137023276627601257325925519566220247124751398891221069403193240\
41688318583612166708334763727216738353107304842707002261430265483385\
20637683911007815690066342722080690052836580858013635214371395680329\
58941156051513954932674117091883540235576934400000000000000000000000\
00000000000000000000000000000000000000000
was quite a strain on my poor system!