Search code examples
c++recursionnumberscatalan

Calculate the nth Catalan number


I wrote some code to calculate the Nth catalan number. However, it isn't returning the correct result when N=20 and onwards. The results when N<20 is correct though, so I'm not sure what is wrong.

So, when N=20, its supposed to return 6564120420, but it returns 2269153124 for me.

Can someone point me in the right direction?

#include <iostream>

using namespace std;

unsigned long int countTree(unsigned int N)
{
    //used to store catalan numbers
    unsigned long int catalan[N+1];

    //N(0)=N(1)=1
    catalan[0]=catalan[1]=1;    
    int i,j;

    for(i=2;i<=N;i++)
    {
        catalan[i]=0;
        for(j=0;j<i;j++)
        {
            catalan[i]+=catalan[j]*catalan[i-j-1];
        }
    }
    return catalan[N];
}

int main()
{
    unsigned int x;
    cout<<"Input N:"<<endl;
    cin>>x;
    unsigned long int result=countTree(x);
    cout<<result<<endl;
    return 0;
}

Solution

  • You're exceeding the maximum size those variable types let you store.

    The long long type is your best bet.

    You can have a look here on what the max values for different types of integers are: http://www.cplusplus.com/reference/climits/