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?
bc
to do the calculation:echo '3706907995955475988644381 ^ 2' | bc