mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
refactor: improving GenericRoot (#6365)
refactor: improving GenericRoot
This commit is contained in:
committed by
GitHub
parent
7590d8234f
commit
dba2d869f2
@@ -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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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);
|
||||
int number = Math.abs(n);
|
||||
if (number < BASE) {
|
||||
return number;
|
||||
}
|
||||
if (n > base) {
|
||||
return genericRoot(sumOfDigits(n));
|
||||
}
|
||||
return n;
|
||||
return genericRoot(sumOfDigits(number));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user