-
Notifications
You must be signed in to change notification settings - Fork 88
/
CatalanNumbers.java
37 lines (35 loc) · 929 Bytes
/
CatalanNumbers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Calculate Catalan Numbers
*/
public final class CatalanNumbers {
private CatalanNumbers() {
}
/**
* Calculate the nth Catalan number using a recursive formula.
*
* @param n the index of the Catalan number to compute
* @return the nth Catalan number
*/
public static long catalan(final int n) {
if (n < 0) {
throw new IllegalArgumentException("Index must be non-negative");
}
return factorial(2 * n) / (factorial(n + 1) * factorial(n));
}
/**
* Calculate the factorial of a number.
*
* @param n the number to compute the factorial for
* @return the factorial of n
*/
private static long factorial(final int n) {
if (n == 0 || n == 1) {
return 1;
}
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}