- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathCatalanNumbers.java
39 lines (36 loc) · 963 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
38
39
packagecom.thealgorithms.maths;
/**
* Calculate Catalan Numbers
*/
publicfinalclassCatalanNumbers {
privateCatalanNumbers() {
}
/**
* Calculate the nth Catalan number using a recursive formula.
*
* @param n the index of the Catalan number to compute
* @return the nth Catalan number
*/
publicstaticlongcatalan(finalintn) {
if (n < 0) {
thrownewIllegalArgumentException("Index must be non-negative");
}
returnfactorial(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
*/
privatestaticlongfactorial(finalintn) {
if (n == 0 || n == 1) {
return1;
}
longresult = 1;
for (inti = 2; i <= n; i++) {
result *= i;
}
returnresult;
}
}