# Factorial of certain numbers yield negative values

Here is the code for my bash script to calculate factorials

``````read -p "Please enter the number " number
while ([ \$number -gt 0 ])
do
factorial=1
for ((i=\$number;i > 0;i--))
do
factorial=\$((factorial * \$i))
done
echo "The factorial of the " \$number " is " \$factorial
number=\$((number - 1))
done
``````

This prints out the factorial of all the numbers ranging from {input:1} Everything looks right except for the factorial of a few. The output is given below.

As you can see the factorials of certain numbers are negative values. I understand from the online forums that the bash script usually breaks when calculating factorial of bigger numbers but these negative values don't seem to be common as far as I could dig online. If someone could throw some light on the reason for it, it could greatly help me in my learning. Thank you!

• Everything looks right, except that the results for values after 20 are wrong — and that should give you a hint as to what’s going on here... Dec 7, 2017 at 14:55

## 1 Answer

bash arithmetic is done over signed 64-bits integers, so the maximum number is:

``````\$ max=\$(( (1<<63) - 1 )); echo "\$max"
9 223 372 036 854 775 807
``````

If you go over it, you start from the opposite range, that is negative numbers.

``````\$ echo \$(( \$max + 1 ))
-9 223 372 036 854 775 808
``````

That is exactly as the overflow of integers is managed in the C language.

For factorials, `20!` is still below it, but not `21!`

• And see `bc`, `dc`, `python`, `gawk -M`, `perl -Mbignum`... for arbitrary precision. Dec 7, 2017 at 15:19
• @Ammu Remember to accept the correct answer! Dec 7, 2017 at 16:29