Practice › Basics
Nth Catalan Number
Medium · Basics · Asked at Amazon, Google, Microsoft
The Catalan numbers 1, 1, 2, 5, 14, 42, … count balanced bracket strings, binary search tree shapes and many other things: C(n) = (2n)! / ((n + 1)! · n!). Print C(n) modulo 10^9 + 7.
Input
A single integer n.
Output
C(n) modulo 10^9 + 7.
Constraints
- 0 ≤ n ≤ 10^6
Compute factorials up to 2n modulo p = 10^9 + 7, and divide using modular inverses (Fermat: x^(p−2)), since p is prime and larger than 2n.
Example 1
Input
4
Output
14
Example 2
Input
0
Output
1
Hints
- C(n) = (2n)! / ((n + 1)! · n!).
- Division modulo a prime p is multiplication by the modular inverse.
- Fermat: x^(p − 2) mod p is the inverse of x.
Approach
Compute (2n)!, n! and (n + 1)! modulo p = 10^9 + 7 in one loop up to 2n. Then C(n) = (2n)! · inverse(n! · (n + 1)! mod p) mod p, with the inverse from fast exponentiation. Since 2n < p, none of the factorials is divisible by p, so the inverses exist. C(0) = 1.
Complexity: O(n + log p) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007LL;
long long power(long long b, long long e) {
long long r = 1;
b %= MOD;
while (e) {
if (e & 1) r = r * b % MOD;
b = b * b % MOD;
e >>= 1;
}
return r;
}
int main() {
long long n;
cin >> n;
long long f = 1, fn = 1, fn1 = 1, f2n = 1;
for (long long i = 1; i <= 2 * n + 1; i++) {
f = f * i % MOD;
if (i == n) fn = f;
if (i == n + 1) fn1 = f;
if (i == 2 * n) f2n = f;
}
cout << f2n * power(fn * fn1 % MOD, MOD - 2) % MOD << "\n";
return 0;
}Python solution
MOD = 10**9 + 7
n = int(input())
f = fn = fn1 = f2n = 1
for i in range(1, 2 * n + 2):
f = f * i % MOD
if i == n:
fn = f
if i == n + 1:
fn1 = f
if i == 2 * n:
f2n = f
print(f2n * pow(fn * fn1 % MOD, MOD - 2, MOD) % MOD)Java solution
import java.util.*;
public class Main {
static final long MOD = 1000000007L;
static long power(long b, long e) {
long r = 1;
b %= MOD;
while (e > 0) {
if ((e & 1) == 1) r = r * b % MOD;
b = b * b % MOD;
e >>= 1;
}
return r;
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
long f = 1, fn = 1, fn1 = 1, f2n = 1;
for (long i = 1; i <= 2 * n + 1; i++) {
f = f * i % MOD;
if (i == n) fn = f;
if (i == n + 1) fn1 = f;
if (i == 2 * n) f2n = f;
}
System.out.println(f2n * power(fn * fn1 % MOD, MOD - 2) % MOD);
}
}