Skip to content
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
Prev Previous commit
Next Next commit
refactor: simplify genericRoot by using recursion
  • Loading branch information
vil02 committed Jul 31, 2023
commit 6ec1b90e2dcce1ad65381dc502e07e9d324143cb
20 changes: 11 additions & 9 deletions src/main/java/com/thealgorithms/maths/GenericRoot.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,21 @@ public static void main(String[] args) {
System.out.println("Generic root of " + number2 + " is: " + result2);
}

private static int sumOfDigits(int n) {
assert n >= 0;
if (n < 10) {
return n;
}
return n % 10 + sumOfDigits(n / 10);
}

public static int genericRoot(int n) {
if (n < 0) {
return genericRoot(-n);
}
int root = 0;
while (n > 0 || root > 9) {
if (n == 0) {
n = root;
root = 0;
}
root += n % 10;
n /= 10;
if (n > 10) {
return genericRoot(sumOfDigits(n));
}
return root;
return n;
}
}