Skip to content

Commit dba2d86

Browse files
authored
refactor: improving GenericRoot (#6365)
refactor: improving GenericRoot
1 parent 7590d82 commit dba2d86

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed
Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,48 @@
11
package com.thealgorithms.maths;
22

3-
/*
4-
* Algorithm explanation:
5-
* https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015.
3+
/**
4+
* Calculates the generic root (repeated digital sum) of a non-negative integer.
5+
* <p>
6+
* For example, the generic root of 12345 is calculated as:
7+
* 1 + 2 + 3 + 4 + 5 = 15,
8+
* then 1 + 5 = 6, so the generic root is 6.
9+
* <p>
10+
* Reference:
11+
* https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/
612
*/
713
public final class GenericRoot {
14+
15+
private static final int BASE = 10;
16+
817
private GenericRoot() {
918
}
1019

11-
private static int base = 10;
12-
20+
/**
21+
* Computes the sum of the digits of a non-negative integer in base 10.
22+
*
23+
* @param n non-negative integer
24+
* @return sum of digits of {@code n}
25+
*/
1326
private static int sumOfDigits(final int n) {
1427
assert n >= 0;
15-
if (n < base) {
28+
if (n < BASE) {
1629
return n;
1730
}
18-
return n % base + sumOfDigits(n / base);
31+
return (n % BASE) + sumOfDigits(n / BASE);
1932
}
2033

34+
/**
35+
* Computes the generic root (repeated digital sum) of an integer.
36+
* For negative inputs, the absolute value is used.
37+
*
38+
* @param n integer input
39+
* @return generic root of {@code n}
40+
*/
2141
public static int genericRoot(final int n) {
22-
if (n < 0) {
23-
return genericRoot(-n);
24-
}
25-
if (n > base) {
26-
return genericRoot(sumOfDigits(n));
42+
int number = Math.abs(n);
43+
if (number < BASE) {
44+
return number;
2745
}
28-
return n;
46+
return genericRoot(sumOfDigits(number));
2947
}
3048
}

0 commit comments

Comments
 (0)