Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables Multiplication for the factorial calculation

I'm making a script that calculates the factorial for a given number, but I'm having some problems with the multiplication.

Note: the factorial for is given by: 9!=9*8*7*6*5*4*3*2*1

Here's my code:

#!/bin/bash  echo "Insert an Integer"  read input  if ! [[ "$input" =~ ^[0-9]+$ ]] ; then    exec >&2; echo "Error: You didn't enter an integer"; exit 1 fi  function factorial { while [ "$input" != 1 ]; do     result=$(($result * $input))     input=$(($input-1)) done } factorial echo "The Factorial of " $input "is" $result 

it keeps giving me errors of all kinds for different multiplication technics :/

Currently the output is:

joaomartinsrei@joaomartinsrei ~/Área de Trabalho/Shell $  ./factorial.sh Insert an Integer 3 ./factorial.sh: line 15: * 3: syntax error: operand expected (error token is "* 3") The factorial of 3 is 
like image 358
UraniumSnake Avatar asked Mar 04 '13 23:03

UraniumSnake


People also ask

Can you multiply factorials in statistics?

You can also multiply factorials by hand. The easiest way to do it is to calculate each factorial individually, and then multiply their products together. You can also use certain rules of factorials to pull out common factors, which can simplify the multiplication process.

What is the formula for calculating factorials?

Calculation of Factorial The factorial of n is denoted by n! and calculated by multiplying the integer numbers from 1 to n. The formula for n factorial is n! = n × (n - 1)!. Example:If 8! is 40,320 then what is 9!?


1 Answers

The main problem is that you never initialize result (to 1), so this:

result=$(($result * $input)) 

is equivalent to this:

result=$(( * $input)) 

which is not a valid arithmetic expression.

like image 87
ruakh Avatar answered Sep 22 '22 21:09

ruakh