To find a digital roots of an integer is a very common question in high school when doing introductory programming. Digital roots are defined as follows. First an integer is taken if the number of digits are greater than 1, then the sum of its digits are done, if the sum has more than one digits then again the sum of digits are done, and so on until a sum of digit has only 1 digit. This last value of the sum of digits containing a one digit value is defined as the digital root of a number. First we describe in brief what a digital root is then present a shell script.
For example the Digital Root of the integer 999 and 35 will be calculated as below
n=999 n=9+9+9=27 n=2+7=9 n=9 is the digital root of 999 n=35 n=3+5=8 n=8 is the digital root of 8
So the method is simply calculate the sum of digits of an integer get the answer and again calculate the sum of digits of it repeatedly until an a sum of digit is not of one length.
Shell Script
Here is the shell script
#!/bin/bash #Get the first parameter number="$1" #Check for NULL input if [ $# -eq 0 -o -z "$number" ] then echo "Syntax: $0 integer" exit fi #Check for valid integer if [[ "$number" == *[^0-9]* ]] then echo "\"$number\" is not a valid integer" exit else : fi #Back up the number as it will be over written number_bak="$number" #initilize n with the length of the number string #NOTE: The length of the string is without the newline char n="${#number}" #Assign the initial number as digital_root. digital_root="$number" #loop until we do not get a number of length 1 while [ $n -ne 1 ] do #Initilizations for inner loop digital_root=0 i=1 #Make the sum of the digits while [ $i -le $n ] do current_digit=$(echo "$number" | cut -b$i) digital_root=$(($digital_root+$current_digit)) i=$(($i+1)) done #Update number with the new sum of digits #and update n with new length number="$digital_root" n="${#number}" done echo "Digital Root of $number_bak = $digital_root"
At the beginning the code tests if the input integer is a valid integer and also if there is a NULL input and then proceeds.
The digital_root variable is assigned an initial value of the input number, this is because when the input integer would be of length one it would the the digital root of itself and thus not enter the while loop. In this case assigning digital_root=$number would come with the correct result.
To know what is the use of digital roots and also to know more about them get into
http://en.wikipedia.org/wiki/Digital_root
Update
2.3.2010: Old code came with wrong output with single digit input. Fixed. And NULL input check added.