Skip to content

refactor: improving GenericRoot #6365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 31 additions & 13 deletions src/main/java/com/thealgorithms/maths/GenericRoot.java
Original file line number Diff line number Diff line change
@@ -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);
}
if (n > base) {
return genericRoot(sumOfDigits(n));
int number = Math.abs(n);
if (number < BASE) {
return number;
}
return n;
return genericRoot(sumOfDigits(number));
}
}
Loading