Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,16 @@ private CatalanNumber() {
* n > 50, BigInteger class should be used instead long
*
* @return catalanArray[n] the nth Catalan number
* @throws IllegalArgumentException if n is negative
*/
static long findNthCatalan(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be non-negative");
}
if (n <= 1) {
return 1;
}

// Array to store the results of subproblems i.e Catalan numbers from [1...n-1]
long[] catalanArray = new long[n + 1];

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
package com.thealgorithms.dynamicprogramming;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

public class CatalanNumberTest {

@Test
public void testCatalanNumber() {
assertEquals(1, CatalanNumber.findNthCatalan(0));
assertEquals(1, CatalanNumber.findNthCatalan(1));
assertEquals(42, CatalanNumber.findNthCatalan(5));
assertEquals(16796, CatalanNumber.findNthCatalan(10));
}

@Test
public void testNegativeInput() {
assertThrows(IllegalArgumentException.class, () -> CatalanNumber.findNthCatalan(-1));
}
}
Loading