Catalan numbers#9643

Catalan numbers (Editorial)

Let's rewrite the recurrence relation as follows:

с_0 = 1, \\ с_n = c_0c_{n-1} + c_1c_{n-2} + c_2c_{n-3} + ... + c_{n-1}c_0,~if~n > 0

For example,

Since the value of с_n is computed based on all previous values c_0, c_1, c_2, ..., c_{n-1}, we will store the Catalan numbers in a linear array.

Algorithm implementation

Declare an array , where we'll store the Catalan numbers: cat[i] = c_i.

long long cat[10001];

Read the input data.

scanf("%lld %lld", &n, &m);

Compute the Catalan numbers using the recurrence relation.

cat[0] = 1;
for (i = 1; i <= n; i++)
{
  for (j = 0; j < i; j++)
    cat[i] = (cat[i] + cat[j] * cat[i - j - 1]) % m;
}

Print the -th Catalan number.

printf("%lld\n", cat[n]);

Python implementation

Read the input data.

n, m = map(int, input().split())

Store the values of the Catalan numbers in the list , where cat[i] = c_i.

cat = [0] * (n + 1)

Compute the Catalan numbers using the recurrence relation.

cat[0] = 1
for i in range(1, n + 1):
  for j in range(i):
    cat[i] = (cat[i] + cat[j] * cat[i - j - 1]) % m

Print the -th Catalan number.

print(cat[n])