Digit product with shell script
How to get product of 1 number in bash? (12345> 1x2x3x4x5)
I am trying to get a script to do multiplication, I tried to elude * char but no luck, I also tried messing around with expr.
echo -n "Enter number "
read n
len=$(echo $n | wc -c)
len=$(( $len - 1 ))
for (( i=1; i <= $len; i++ ))
do
prod=$(($prod \* $(echo $n | cut -c $i) ))
done
echo "Product of $n is $prod"
source to share
You can get string length from parameter expansion, no need to call external tools.
#!/bin/bash
read -p 'Enter number: ' n
product=1
for (( i=0; i < ${#n}; ++i )) ; do
d=${n:i:1}
(( product *= d ))
done
printf '%d\n' $product
And, for fun, using Perl:
perl -MList::Util=product -le 'print product(split //, shift)' -- "$n"
source to share
As I understand it, you want to get the value of the multiplication of digits in a number
Let's say you have a number:
number=12345
You must insert * between numbers:
echo $number | sed 's/\([0-9]\)/\1*/g'
We will get the line:
1*2*3*4*5*
We don't need the latest asterics - let's remove it:
echo $number | sed 's/\([0-9]\)/\1*/g' | sed 's/.$//g'
We get the following:
1*2*3*4*5
We can now redirect it to calc:
echo $number | sed 's/\([0-9]\)/\1*/g' | sed 's/.$//g' | calc -p
This is stdout:
120
source to share
\*
is wrong in arithmetic, it must be *
one. But even then, running your code gives:
$ bash product.sh
Enter number 12
product.sh: line 10: * 1 : syntax error: operand expected (error token is "* 1 ")
Product of 12 is
The reason for the error is that the variable is $prod
not set to an initial value before being expanded to an empty value, for example try in your terminal:
$ echo $prod
$
In your script, you must set prod
to an initial value before using it the first time. It should be:
echo -n "Enter number "
read n
len=$(echo $n | wc -c)
len=$(( $len - 1 ))
prod=1
for (( i=1; i <= $len; i++ ))
do
prod=$(($prod * $(echo $n | cut -c $i) ))
done
echo "Product of $n is $prod"
There are a few more problems with your code:
- always puts the shebang line at the top
- always double quote variables
- use
$
for variables is not required in arithmetic expressions inBash
source to share