Finding the digit root of a number

Posted by Jessica M. on Stack Overflow See other posts from Stack Overflow or by Jessica M.
Published on 2012-10-24T06:26:53Z Indexed on 2012/10/24 11:01 UTC
Read the original article Hit count: 195

Filed under:
|

Study question is to find the digit root of a already provided number. The teacher provides us with the number 2638. In order to find the digit root you have to add each digit separately 2 + 6 + 3 + 8 = 19. Then you take the result 19 and add those two digits together 1 + 9 = 10. Do the same thing again 1 + 0 = 1. The digit root is 1.

My first step was to use the variable total to add up the number 2638 to find the total of 19. Then I tried to use the second while loop to separate the two digits by using the %

I have to try and solve the problem by using basic integer arithmetic (+, -, *, /).
1.Is it necessary and or possible to solve the problem using nested while loops?
2.Is my math correct?
3. As I wrote it here it does not run in Eclipse. Am I using the while loops correctly?

import acm.program.*;


public class Ch4Q7 extends ConsoleProgram {
   public void run(){
      println("This program attempts to find the digit root of your number: ");

      int n = readInt("Please enter your number: "); 

      int total = 0;

      int root = total;


      while (n > 0 ){
        total = total + (n %10);
    n = (n / 10);

    }   

   while ( total > 0 ){
     root = total; 
     total = ((total % 10) + total / 10); 
    }


     println("your root should be " + root);
}

}

© Stack Overflow or respective owner

Related posts about java

Related posts about math