|
1 | 1 | package com.thealgorithms.maths;
|
2 | 2 |
|
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/ |
6 | 12 | */
|
7 | 13 | public final class GenericRoot {
|
| 14 | + |
| 15 | + private static final int BASE = 10; |
| 16 | + |
8 | 17 | private GenericRoot() {
|
9 | 18 | }
|
10 | 19 |
|
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 | + */ |
13 | 26 | private static int sumOfDigits(final int n) {
|
14 | 27 | assert n >= 0;
|
15 |
| - if (n < base) { |
| 28 | + if (n < BASE) { |
16 | 29 | return n;
|
17 | 30 | }
|
18 |
| - return n % base + sumOfDigits(n / base); |
| 31 | + return (n % BASE) + sumOfDigits(n / BASE); |
19 | 32 | }
|
20 | 33 |
|
| 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 | + */ |
21 | 41 | 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; |
27 | 45 | }
|
28 |
| - return n; |
| 46 | + return genericRoot(sumOfDigits(number)); |
29 | 47 | }
|
30 | 48 | }
|
0 commit comments