Q14. Find the digital root of a given number.
Digital Root: (also repeated digital sum) of a number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.
For example, the digital root of 65,536 is 7, because 6+5+5+3+6 = 25 and 2+5 = 7.
Answer:
public class Mathematics14 {
public static int getDigitalRoot(int n) {
if (n <= 0) {
System.out.println("Digital root is not defined for negative numbers");
return 0;
}
int digitalRoot = n % 9;
if (digitalRoot == 0) {
return 9;
}
return digitalRoot;
}
public static void main(String[] args) {
System.out.println(getDigitalRoot(15));
System.out.println(getDigitalRoot(181));
System.out.println(getDigitalRoot(72));
System.out.println(getDigitalRoot(65536));
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.