0

So I am trying to write a script that prints the sum of every digit in a number, to the power of another number.

So for example, if the input is: script 123 2 than the script calculates 1^2 + 2^2 + 3^2 and outputs 14.

My script:

Num=$1
s=0
while [ $Num -gt 0 ]
do
   k=$(( $Num % 10 ))

   Num=$(( $Num / 10 ))

   s=$(( $s + ($k**$2)))
done
echo $s

This works for smaller numbers, but numbers like "3706907995955475988644381" cause the following error: line 5: [: 3706907995955475988644381: integer expression expected

How can I make this script work with big numbers?

2
  • 5
    bash can only handle 64-bit integers. If you need arbitrarily large numbers, you have to choose a different tool. Nov 23, 2022 at 14:27
  • 3
    Try using bc to do the calculation: echo '3706907995955475988644381 ^ 2' | bc
    – Panki
    Nov 23, 2022 at 14:29

1 Answer 1

1

You can handle the input as a string, calculate its length and use substring parameter expansion to extract single digits.

Num=$1
Exp=$2
s=0
# string length
i=${#Num}
while [ $i -gt 0 ]
do
   # index is 0-based, decrement before using
   : $((i--))
   # 1 character at index i
   k=${Num:$i:1}

   s=$(( $s + ($k**$Exp)))
done
echo $s

Note: The code lacks error handling. You might get unexpected results if the input contains non-digit characters, and the calculation might overflow for very long numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.