Skip to content

Commit 2500ee0

Browse files
committed
feature/CatalanNumbers
1 parent be70801 commit 2500ee0

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* Calculate Catalan Numbers
5+
*/
6+
public final class CatalanNumbers {
7+
private CatalanNumbers() {
8+
}
9+
10+
/**
11+
* Calculate the nth Catalan number using a recursive formula.
12+
*
13+
* @param n the index of the Catalan number to compute
14+
* @return the nth Catalan number
15+
*/
16+
public static long catalan(final int n) {
17+
if (n < 0) {
18+
throw new IllegalArgumentException("Index must be non-negative");
19+
}
20+
return factorial(2 * n) / (factorial(n + 1) * factorial(n));
21+
}
22+
23+
/**
24+
* Calculate the factorial of a number.
25+
*
26+
* @param n the number to compute the factorial for
27+
* @return the factorial of n
28+
*/
29+
private static long factorial(final int n) {
30+
if (n == 0 || n == 1) {
31+
return 1;
32+
}
33+
long result = 1;
34+
for (int i = 2; i <= n; i++) {
35+
result *= i;
36+
}
37+
return result;
38+
}
39+
40+
/**
41+
* Main method to test the Catalan number calculation.
42+
*/
43+
public static void main(String[] args) {
44+
for (int i = 0; i <= 10; i++) {
45+
System.out.println("Catalan number " + i + " is: " + catalan(i));
46+
}
47+
}
48+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertAll;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
/**
10+
* Test class for CatalanNumbers
11+
*/
12+
class CatalanNumbersTest {
13+
14+
@Test
15+
void testCatalanNumbers() {
16+
assertEquals(1, CatalanNumbers.catalan(0)); // C(0) = 1
17+
assertEquals(1, CatalanNumbers.catalan(1)); // C(1) = 1
18+
assertEquals(2, CatalanNumbers.catalan(2)); // C(2) = 2
19+
assertEquals(5, CatalanNumbers.catalan(3)); // C(3) = 5
20+
assertEquals(14, CatalanNumbers.catalan(4)); // C(4) = 14
21+
assertEquals(42, CatalanNumbers.catalan(5)); // C(5) = 42
22+
assertEquals(132, CatalanNumbers.catalan(6)); // C(6) = 132
23+
assertEquals(429, CatalanNumbers.catalan(7)); // C(7) = 429
24+
assertEquals(1430, CatalanNumbers.catalan(8)); // C(8) = 1430
25+
assertEquals(4862, CatalanNumbers.catalan(9)); // C(9) = 4862
26+
assertEquals(16796, CatalanNumbers.catalan(10)); // C(10) = 16796
27+
}
28+
29+
@Test
30+
void testIllegalInput() {
31+
assertAll(
32+
() -> assertThrows(IllegalArgumentException.class, () -> CatalanNumbers.catalan(-1)),
33+
() -> assertThrows(IllegalArgumentException.class, () -> CatalanNumbers.catalan(-5))
34+
);
35+
}
36+
}

0 commit comments

Comments
 (0)