- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathGenericRoot.java
30 lines (26 loc) · 804 Bytes
/
GenericRoot.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
packagecom.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.
*/
publicfinalclassGenericRoot {
privateGenericRoot() {
}
privatestaticintbase = 10;
privatestaticintsumOfDigits(finalintn) {
assertn >= 0;
if (n < base) {
returnn;
}
returnn % base + sumOfDigits(n / base);
}
publicstaticintgenericRoot(finalintn) {
if (n < 0) {
returngenericRoot(-n);
}
if (n > base) {
returngenericRoot(sumOfDigits(n));
}
returnn;
}
}