Jay Gorio
Jay Gorio

Reputation: 335

How to get the factors of a given number in Unix?

I have this concern, when getting the factors of a number. My code gives me the total numbers of all factors of a number.What I want is it should only display the factors of that number, not the total. For example I input 9 the output should be 1,3 and 9.

My code

echo -n " enter a no. "
read n
i=1
mul=1
until [ $i -gt $n ]
do
mul=`expr $mul \* $i `
i=`expr $i + 1 `
done 
echo " factorial of $n is $mul "

Upvotes: 1

Views: 7963

Answers (1)

Gnubie
Gnubie

Reputation: 2607

Assuming that the user enters the number in its simplest form, e.g. 9 instead of 09.0, this works:

echo -n " enter a no. "
read n
for i in $(seq 1 $n)
do
 [ $(expr $n / $i \* $i) == $n ] && echo $i
done

though a bit slowly for large numbers.

Upvotes: 2

Related Questions