Here is the code for my bash script to calculate factorials

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

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. Output of the code to calculate factorial

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!

  • 3
    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... – Stephen Kitt Dec 7 '17 at 14:55

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.