views:

39

answers:

2

Hi, I was writing a script to check if a number is Armstrong or not. This is my Code

echo "Enter Number"
read num
sum=0
item=$num
while [ $item -ne 0 ]
do
rem='expr $item % 10'
cube='expr $rem \* $rem \* $rem'
sum='expr $sum + $cube'
item='expr $item / 10'
done
if [ $sum -eq $num ]
then
echo "$num is an Amstrong Number"
else
echo "$num is not an Amstrong Number"
fi

After I run this script,

$ ./arm.sh

I always get these errors

line 5: [: too many arguments

line 12: [: too many arguments

I am on cygwin.

+1  A: 

Those are straight quotes in your expr commands. To evaluate an expression, you need to use backquotes:

rem=`expr $item % 10`
Kilian Foth
great thanks :) This works.. 4 mins go and I will choose it as right answer :)
atif089
or preferably (for readability) use $(...) as in: rem=$(expr $item % 10)
Adrian Pronk
A: 

The errors are from missing quotes in the [ ] command: [ "$item" -ne 0 ]. However, do not use [ ] for arithmetic expressions. Instead, use (( )):

while ((item != 0)); do ... done

Also, your calculation for Armstrong number seems to be wrong. Why are you cubing? You need to check that num has exactly three digits in that case, do you not? http://en.wikipedia.org/wiki/Narcissistic_number

Assuming you really meant the standard definition of "Armstrong number", this should work:

#!/bin/sh -eu

is_armstrong() {
  local num digits sum
  num="$1"
  case "$num" in
  # Reject invalid numerals.
  (*[^0-9]*|0?*) echo "$num: invalid numeral." >&2; return 1;;
  esac
  digits=${#num}
  sum=0
  while ((num > 0)); do
    ((sum += (num % 10) ** digits))
    ((num /= 10))
  done
  ((sum == $1))
}

# Prompt the user for a number if none were give on the command line.
if (($# == 0)); then
  read -p "Enter a natural number: " num
  set -- "$num"
fi

# Process all the numbers.
for num in "$@"; do
  num=$((num + 0))  # canonicalize the numeric representation
  if is_armstrong "$num"; then
    echo "$num is an Amstrong Number"
  else
    echo "$num is not an Amstrong Number"
  fi
done
Mark Edgar