catalan

nth Catalan number using Combinations


I have written a c++ program to find n-th catalan number by using combinations but I am always getting output 0. Please point out mistakes in this code:

#include <iostream>
using namespace std;

int fact(unsigned int x)              
{
     unsigned long long f = 1;
     for (int i = 1; i <= x; i++)
     {
         f = f*i;
     }
     return f;
}

int comb(int y, int z)      
{
    unsigned long long int c;
    c = fact(y) / (fact(z)*fact(y - z));
    return c;
}

int catalan(int b)
{   
    unsigned long long int a;
    a = (1 / (b + 1))*(comb((2 * b), b));
    return a;
}

int main()
{   
    int n;
    cout << "enter value of n for nth catalan number=";
    cin >> n;
    cout << n << " Catalan number=" << catalan(n) << endl;
    return 0;
}

Solution

  • (1 / (b + 1)) is always going to be zero. Instead use

    a = comb(2 * b, b) / (b + 1);
    

    Also, you do your calculations using unsigned long long. Why not use that as return type instead of int.