File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/dynamicprogramming
test/java/com/thealgorithms/dynamicprogramming Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -21,8 +21,16 @@ private CatalanNumber() {
2121 * n > 50, BigInteger class should be used instead long
2222 *
2323 * @return catalanArray[n] the nth Catalan number
24+ * @throws IllegalArgumentException if n is negative
2425 */
2526 static long findNthCatalan (int n ) {
27+ if (n < 0 ) {
28+ throw new IllegalArgumentException ("n must be non-negative" );
29+ }
30+ if (n <= 1 ) {
31+ return 1 ;
32+ }
33+
2634 // Array to store the results of subproblems i.e Catalan numbers from [1...n-1]
2735 long [] catalanArray = new long [n + 1 ];
2836
Original file line number Diff line number Diff line change 11package com .thealgorithms .dynamicprogramming ;
22
33import static org .junit .jupiter .api .Assertions .assertEquals ;
4+ import static org .junit .jupiter .api .Assertions .assertThrows ;
45
56import org .junit .jupiter .api .Test ;
67
78public class CatalanNumberTest {
89
910 @ Test
1011 public void testCatalanNumber () {
12+ assertEquals (1 , CatalanNumber .findNthCatalan (0 ));
13+ assertEquals (1 , CatalanNumber .findNthCatalan (1 ));
1114 assertEquals (42 , CatalanNumber .findNthCatalan (5 ));
1215 assertEquals (16796 , CatalanNumber .findNthCatalan (10 ));
1316 }
17+
18+ @ Test
19+ public void testNegativeInput () {
20+ assertThrows (IllegalArgumentException .class , () -> CatalanNumber .findNthCatalan (-1 ));
21+ }
1422}
You can’t perform that action at this time.
0 commit comments