Calculate the nth Catalan number

僤鯓⒐⒋嵵緔 提交于 2019-12-11 08:39:46

问题


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;
}

回答1:


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/




回答2:


use "unsigned long long" in place of "unsigned int".`

#include <iostream>

using namespace std;

unsigned long long countTree(unsigned int N)
{
    //used to store catalan numbers
    unsigned long long catalan[N+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;
    cout << countTree(x) << endl;
    return 0;
}


来源:https://stackoverflow.com/questions/25539844/calculate-the-nth-catalan-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!