'What is wrong with my factorial code in Linux? [duplicate]

#!/bin/bash
echo "Enter a number: "
read number
factorial=1
function FactorialMethod()
{
num=$1
while [[ $num -ge 1 ]]
do
    factorial=$(( $factorial*$num ))
    num=$(($num - 1))
done
return $factorial
}
FactorialMethod $number
result=$?
echo "Factorial of "$number" is "$result
  • When I run this code and I input numbers from 0 to 5 I'm getting correct answers. However when I input numbers from 6 and above I'm getting wrong answers... What is wrong with my code?

  • I'm new to StackOverflow so I'm sorry if this was a repeated question and thank you for your help :)



Solution 1:[1]

Posting as a community answer since this is an obvious duplicate


Return value in a Bash function

Although Bash has a return statement, the only thing you can specify with it is the function's own exit status (a value between 0 and 255, 0 meaning "success").

So return is not what you want.


The reason why it works for 5, but not for 6 is because 5! is smaller then 255. but 6! is 720


So replace the following

# Wrong
return $factorial

# Correct
echo $factorial

And

# Wrong
FactorialMethod $number
result=$?

# Correct
result=$(FactorialMethod $number)

Final code:

#!/bin/bash

echo "Enter a number: "
read number
factorial=1

function FactorialMethod() {
    num=$1
    while [[ $num -ge 1 ]]
    do
        factorial=$(( $factorial*$num ))
        num=$(($num - 1))
    done
    echo $factorial
}

result=$(FactorialMethod $number)
echo "Factorial of "$number" is "$result

Solution 2:[2]

As described at this article,

Bash functions, unlike functions in most programming languages do not allow you to return a value to the caller.

So,

The simplest way to return a value from a bash function is to just set a global variable to the result. Since all variables in bash are global by default

In this case, you could simply call the method, and then check the value of the (global) variable factorial:

#!/bin/bash
echo "Enter a number: "
read number
factorial=1 # here the global variable is defined
function FactorialMethod()
{
  num=$1
  while [[ $num -ge 1 ]]
  do
      factorial=$(( $factorial*$num )) # this line will update the global variable
      num=$(($num - 1))
  done
}
FactorialMethod $number # calls the method so that the value of 'factorial' is updated properly
echo "Factorial of "$number" is "$factorial # 'factorial' variable will have the correct value

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Marcos Parreiras