I need some help checking over my program to find the digit root. If a user enters 5635 the digit root is 1. To find the digit root of a number you add all the digits in the number 5 + 6 + 3 + 5 and you get the result of 19. Then you add the result 1 + 9 = 10. Then you add 1 + 0 until you get 1 which is your digit root.
- Do i have the right approach or is my approach to the question totally off?
- Why am i getting 0 as the result instead of the correct answer of 1?
import acm.program.*;
public class DigitRoot extends ConsoleProgram {
public void run() {
println("this program attemts to find the digit root a user enters.");
int n = readInt("please enter any positive integer: ");
int dsum = 0;
int sumtotal = 0;
int threesum = 0;
int foursum = 0;
while (n > 0) {
dsum += n % 10;
n /= 10;
if (dsum > 9) {
sumtotal = (dsum / 10) + (dsum % 10);
} else if (sumtotal > 9) {
threesum = (sumtotal / 10) + (sumtotal % 10);
} else if (threesum > 9) {
foursum = (threesum / 10) + (threesum % 10);
} else if (foursum < 9) {
println("your digit root is" + foursum);
} else {
println("this program is borken.");
}
}
}
}
Example using a recursion – I calculate the sum of the figures by using a String: it is not very efficient but is (slightly) easier. Feel free to improve by using
n % 10in a loop.