diff --git a/src/main/java/com/thealgorithms/maths/GenericRoot.java b/src/main/java/com/thealgorithms/maths/GenericRoot.java index 07f4756f93f8..e13efe5a77e0 100644 --- a/src/main/java/com/thealgorithms/maths/GenericRoot.java +++ b/src/main/java/com/thealgorithms/maths/GenericRoot.java @@ -1,30 +1,48 @@ package com.thealgorithms.maths; -/* - * Algorithm explanation: - * 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. +/** + * Calculates the generic root (repeated digital sum) of a non-negative integer. + *
+ * For example, the generic root of 12345 is calculated as: + * 1 + 2 + 3 + 4 + 5 = 15, + * then 1 + 5 = 6, so the generic root is 6. + *
+ * Reference: + * https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/ */ public final class GenericRoot { + + private static final int BASE = 10; + private GenericRoot() { } - private static int base = 10; - + /** + * Computes the sum of the digits of a non-negative integer in base 10. + * + * @param n non-negative integer + * @return sum of digits of {@code n} + */ private static int sumOfDigits(final int n) { assert n >= 0; - if (n < base) { + if (n < BASE) { return n; } - return n % base + sumOfDigits(n / base); + return (n % BASE) + sumOfDigits(n / BASE); } + /** + * Computes the generic root (repeated digital sum) of an integer. + * For negative inputs, the absolute value is used. + * + * @param n integer input + * @return generic root of {@code n} + */ public static int genericRoot(final int n) { - if (n < 0) { - return genericRoot(-n); - } - if (n > base) { - return genericRoot(sumOfDigits(n)); + int number = Math.abs(n); + if (number < BASE) { + return number; } - return n; + return genericRoot(sumOfDigits(number)); } }
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: