Skip to content
Merged
Show file tree
Hide file tree
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
fix: handle negative inputs
  • Loading branch information
vil02 committed Jul 31, 2023
commit 3531ea14332df55d80488a7550e25df2e51a5772
3 changes: 3 additions & 0 deletions src/main/java/com/thealgorithms/maths/GenericRoot.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public static void main(String[] args) {
}

public static int genericRoot(int n) {
if (n < 0) {
return genericRoot(-n);
}
int root = 0;
while (n > 0 || root > 9) {
if (n == 0) {
Expand Down
11 changes: 9 additions & 2 deletions src/test/java/com/thealgorithms/maths/GenericRootTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@
import org.junit.jupiter.api.Test;

public class GenericRootTest {
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));
@Test
public void testGenericRoot() {
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));
for (final var tc : testCases.entrySet()) {
assertEquals(tc.getValue(), GenericRoot.genericRoot(tc.getKey()));
}
}
}

@Test
public void testGenericRootWithNegativeInputs() {
for (final var tc : testCases.entrySet()) {
assertEquals(tc.getValue(), GenericRoot.genericRoot(-tc.getKey()));
}
}
}