Why this code is not working?

Hello,

I'm working with factorial code, and thought to do multiple parenthesis arithmetic expression.

So, I got the code working with the following code:

read -p "Enter number: " n
d=1 cnt1=$n cnt2=$cnt1
while [ $cnt2 -gt 1 ]
do
 cnt2=$(($cnt2 - 1)) #eq1
 cnt1=$(($cnt1 * ($cnt2))) #eq2
done
echo $cnt1

And when I want to include eq1 in second argument of eq2 it doesn't work!

Why?

 read -p "Enter number: " n
cnt=$n
cnt1=$cnt
while [ $cnt1 -gt 1 ]
do
cnt=$(($cnt * ($cnt1 - 1)))
done
echo result= $cnt cnt1=$cnt1

in the second code sample you never decrease the loop variable cnt1 so the loop will never finish

how?

Is not the second part of the equation does the decrementing?

cnt=$(($cnt * ($cnt1 - 1)))

I think the part on the right does the same decrementing process as in:

cnt2=$(($cnt2 - 1)) #eq1
 cnt1=$(($cnt1 * ($cnt2))) #eq2

so what I wanted to do is to include eq1 in eq2.

I don't see much difference, only combining 2 equations in one.

What I'm missing here?

These are not equations, but assignments. In the first example, the value is never assigned to cnt1 (only to variable cnt ), whereas in the 2nd example, it is..

In the first code the loop counter which is cnt2 and assigned by cnt1
In the second code the loop counter is cnt1 and assigned by cnt

I have three variables in both codes

So In the first code decrementing

The first code: cnt2=$(($cnt2 - 1)) 

is before the main arithmetic expression

The first code: cnt1=$(($cnt1 * ($cnt2)))

In the second code I want to combine decrementing and main expressions in one arithmetic expression

The second code: cnt=$(($cnt * ($cnt1 - 1)))

The part on the right of the second expression should do the same operation as in the decrementing line of the first code; I think they are the same.

---------- Post updated at 03:38 AM ---------- Previous update was at 01:41 AM ----------

OK I got it!!

You're right the internal variable cnt1 is not assigned to be updated, so I read in a website about assigning variables.

ead -p "Enter number: " n
  2 
  3 cnt=$n
  4 cnt1=$cnt
  5 while [ $cnt1 -gt 1 ]
  6 do
  7 cnt=$(((cnt * (cnt1 -= 1 ))))
  8 done
  9 
 10 echo result= $cnt cnt1=$cnt1

This is the result to get the correct answer.

Thank you,

do you find the following code (which also works for the case where n is 1) easier to understand:

#!/bin/bash
read -p "Enter number: " n
fact=1
i=1
while [ $i -lt $n ]
do	fact=$((fact * (i += 1)))
done
echo "$n! is $fact"

I assume that you're using bash because read -p isn't in the standards and is not accepted by ksh (which would do this with read n?'Enter number: ' ).

Note, however, that if you want to compute factorials larger than 25! on a machine with 64-bit long ints, you'll need to use something with arbitrary precision arithmetic (such as bc or dc ) instead of relying on shell arithmetic.