What is the fastest (known) algorithm to find the n-th Catalan number mod m?

Viewed 5675

The problem is to find the n-th Catalan number mod m, where m is NOT prime, m = (10^14 + 7). Here are the list of methods that I have tried: (max N = 10,000)

  1. Dynamic programming for table look-up, too slow
  2. Use Catalan formula ncr(2*n, n)/(n + 1), again it wasn't fast enough due to the ncr function, can't speed up using exponentiation squaring because m is not prime.
  3. Hardcode a table of pre-generated Catalans, but it failed due to the file size limit.
  4. Recurrence relation C(i,k) = C(i-1,k-1) + C(i-1,k), this is way too slow

So I wonder is there any other faster algorithm to find the n-th Catalan number that I'm not aware of?

Using Dynamic Programming

void generate_catalan_numbers() {
    catalan[1] = 1;
    for (int i = 2; i <= MAX_NUMBERS; i++) {
        for (int j = 1; j <= i - 1; j++) {
            catalan[i] = (catalan[i] + ((catalan[j]) * catalan[i - j]) % MODULO) % MODULO;
        }
        catalan[i] = catalan[i] % MODULO;
    }
}

Using original formula

ull n_choose_r(ull n, ull r) {
    if (n < r)
        return 0;

    if (r > n/2) {
        r = n - r;
    }

    ull result = 1;
    ull common_divisor;
    for (int i = 1; i <= r; ++i) {
        common_divisor = gcd(result, i);
        result /= common_divisor;
        result *= (n - i + 1) / (i / common_divisor);
    }

    return result;
}

Using recurrence relation

ull n_choose_r_relation(ull n, ull r) {
    for (int i = 0; i <= n + 1; ++i) {
        for (int k = 0; k <= r && k <= i; ++k) {
            if (k == 0 || k == i) {
                ncr[i][k] = 1;
            }
            else {
                ncr[i][k] = (ncr[i - 1][k - 1] + ncr[i - 1][k]) % MODULO;
            }
        }
    }

    return ncr[n][r];
}
2 Answers
Related