Skip to content

Commit ee23b6c

Browse files
authored
Add tests for GenericRoot (#4276)
1 parent 087d523 commit ee23b6c

File tree

2 files changed

+42
-18
lines changed

2 files changed

+42
-18
lines changed

src/main/java/com/thealgorithms/maths/GenericRoot.java

+18-18
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,27 @@
44
* Algorithm explanation:
55
* 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.
66
*/
7-
public class GenericRoot {
7+
public final class GenericRoot {
8+
private GenericRoot() {
9+
}
10+
11+
private static int base = 10;
812

9-
public static void main(String[] args) {
10-
int number1 = 1234;
11-
int number2 = 12345;
12-
int result1 = genericRoot(number1);
13-
int result2 = genericRoot(number2);
14-
System.out.println("Generic root of " + number1 + " is: " + result1);
15-
System.out.println("Generic root of " + number2 + " is: " + result2);
13+
private static int sumOfDigits(final int n) {
14+
assert n >= 0;
15+
if (n < base) {
16+
return n;
17+
}
18+
return n % base + sumOfDigits(n / base);
1619
}
1720

18-
private static int genericRoot(int n) {
19-
int root = 0;
20-
while (n > 0 || root > 9) {
21-
if (n == 0) {
22-
n = root;
23-
root = 0;
24-
}
25-
root += n % 10;
26-
n /= 10;
21+
public static int genericRoot(final int n) {
22+
if (n < 0) {
23+
return genericRoot(-n);
24+
}
25+
if (n > base) {
26+
return genericRoot(sumOfDigits(n));
2727
}
28-
return root;
28+
return n;
2929
}
3030
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.thealgorithms.maths;
2+
3+
import static java.util.Map.entry;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
6+
import java.util.Map;
7+
import org.junit.jupiter.api.Test;
8+
9+
public class GenericRootTest {
10+
private final Map<Integer, Integer> testCases = Map.ofEntries(entry(0, 0), entry(1, 1), entry(12345, 6), entry(123, 6), entry(15937, 7), entry(222222, 3), entry(99999, 9));
11+
@Test
12+
public void testGenericRoot() {
13+
for (final var tc : testCases.entrySet()) {
14+
assertEquals(tc.getValue(), GenericRoot.genericRoot(tc.getKey()));
15+
}
16+
}
17+
18+
@Test
19+
public void testGenericRootWithNegativeInputs() {
20+
for (final var tc : testCases.entrySet()) {
21+
assertEquals(tc.getValue(), GenericRoot.genericRoot(-tc.getKey()));
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)