views:

507

answers:

3

Hello

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));
    }
}


A: 

I would take the input in as a String instead. This way, you can simply loop through the String and use Integer.parseInt() to grab each number and add them. You can convert that number again to a String and loop through the code to obtain your digital root.

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

    String num = readLine("Enter the number: ");
    int sum = 10;
    while (num > 9) {
      for (int x = 0; x < num.length(); x++) {
         sum = Integer.parseInt(num.charAt(x));
      }
      num = Integer.toString(sum);
   }
   println("Digital Root is: " + sum);
}
AlbertoPL
+2  A: 

Personally, I do not like your loop, which is essentially two loops (first going over the original digits, then going over the digits of sum) mashed into one. How about a sprinkling of recursion:

private int sumDigits(int in){
   if (i>10)
      return in%10 + sumDigits(in/10);
    return in;
}

private int digitalRoot(int in){
    assert (in > 0) ;
    while (in > 9)  in=sumDigits(in);
    return in;
}
Thilo
Thanks, but I am still a beginner in Java Programming, I haven't yet learned Recursion
Ibn Saeed
Teachers love recursion...
Thilo
the recursion chapter is the last one in my book and sadly the teacher wont teach it. I'll have to go through it myself.
Ibn Saeed
+5  A: 
#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
Tyler
When i searched google, i did find this (1 + (number - 1) % 9). Ill give it a try.
Ibn Saeed
For homework, you are going to have to proof/explain that magic formula, though.
Thilo
This works great, but how do people come out with such algos ?
Ibn Saeed
Its not homework per say, just learning programming by myself by going through all the problems from the book.
Ibn Saeed
This formula resides at the bottom of the page: http://en.wikipedia.org/wiki/Digital_rootIt's quite brilliant.
Tyler
yeah... that's pretty hot.
Victor
+1 for what Wikipedia calls Ramans' formula.
Thilo
@Tyler, how do they come up with such formulas ?When you are programming, do you use other's formula or do you write your own way of solving a problem ?
Ibn Saeed
When writing real code, you should always use well-established algorithms where applicable. No need to re-invent the wheel. However, for homework, they are probably trying to teach you how the wheel works, so you should try to figure the algorithm out yourself. This way, you will learn more, and be able to appreciate the cleverness contained in something like Ramans' formula even more.
Thilo
@IbnI did not come up with this algorithm :-) See above for my personal solution.
Tyler
@Tyler, yes i know that you did not come up with the algo, that is why i said " how do they ". I think you missed that part, nevermind. I appreciate that you edited your answer and included the code without using Raman's formula. This helps as well :)
Ibn Saeed
@Thilo, yes, that is why i also skipped the formula when working on the solution and i opted to solve it through normal programming rather than using an algorithm. Are there any books which explains such algorithms, how they came up with such stuff ?
Ibn Saeed
@IbnOops! Didn't see that.In this case, Ramans' formula isn't really an algorithm in the same way the Pythatgorean theorum isn't really an algorithm. Ramans' formula was most likely derived via pure math.
Tyler
@Tyler, so in terms of programming, is it necessary to know how the formula came about or should the programmer just search and use the algoritm/formula he finds to be suitable for a particular task.
Ibn Saeed
@IbnI'm only 17 and solely self-taught so take my advice with a grain of salt but I would imagine if the advantage of your software hinges on the speed that it does something, writing your own algorithm is a must. If the algorithm is a means to an end, just find a well established one that is fast.Example) If I am writing a game that's going to sell based on how cool it looks, it better look damn better than my competitors and therefore has to be based on my own brand-new-state-of-the-art graphics library. If your game is based on storyline and character depth,
Tyler
using another graphics library is ok.
Tyler
@Tyler, age does not matter, even though you are younger than me. If I get to learn something, ill go ahead :)Thanks for detailed reply though :)
Ibn Saeed