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

Merged
merged 2 commits into from
Jul 12, 2025
Merged
Changes from 1 commit
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
Next Next commit
refactor: improving GenericRoot
  • Loading branch information
alxkm committed Jul 10, 2025
commit 537fb748f3b5fd7860685c017c9b2f1fde5fd9b3
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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

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:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy