Java – Calculating Digital Root, is there a better way

javamath

This is how i calculated the digital root of an integer.


import acm.program.*;

public class Problem7 extends ConsoleProgram
{
    public void run()
    {
        println("This program calculates the digital root of an interger.");

        int num = readInt("Enter the number: ");
        int sum = 0;
        while (true)
        {
            if (num > 0)
            {
                int dsum = num % 10;
                num /= 10;
                sum += dsum;
            }
            else if (sum > 9)
            {
                int dsum = sum % 10;
                sum /= 10;
                sum += dsum;

            } else if (sum <= 9 ) break;
        }
        println("Digital Root is: " + sum);
    }

The program works fine.

Is there a better/shorter way of calculating the digital root of a number. ?


EDIT/ADDED : Here is the implementation of the above problem by using Tyler's answer, it works as well:


import acm.program.*;

public class Problem7 extends ConsoleProgram
{
    public void run()
    {
        println("This program calculates the digital root of an interger.");

        int num = readInt("Enter the number: ");
        println("Digital Root of " + num + " is: " + (1 + (num - 1) % 9));
    }
}

Best Solution

#include <stdio.h>

int main(void)
{
   int number;
   scanf("%d", &number);

   printf("The digital root of %d is %d.", number, (1 + (number - 1) % 9));
}

Had I not been able to find Ramans' formula this is how I would write this program...:

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    int c;
    int number = 0;
    while ((c = getchar()) != EOF)
    {
        if (isdigit(c))
            number += (c - '0');
    }
    if (number <= 9)
    {
        printf("The digital root is %d\n", number);
    }
    else
    {
        printf("%d", number);
    }

}

After compiling, to run this, basically you just chain these together. I believe four is the most you could possibly need for an integer.

$ echo 829382938 | ./digitalroot | ./digitalroot | ./digitalroot | ./digitalroot
Related Question