Add Catalan number (#5846)

This commit is contained in:
UTSAV SINGHAL
2024-10-26 15:40:20 +05:30
committed by GitHub
parent 70adf6f223
commit 1577ec4e62
2 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package com.thealgorithms.maths;
/**
* 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;
}
}