【问题标题】:Calculate the nth Catalan number计算第 n 个加泰罗尼亚数
【发布时间】:2017-02-01 08:10:13
【问题描述】:

我写了一些代码来计算第 N 个加泰罗尼亚语数。但是,当 N=20 及以后,它不会返回正确的结果。 N

所以,当 N=20 时,它应该返回 6564120420,但它为我返回 2269153124。

有人能指出正确的方向吗?

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

【问题讨论】:

    标签: c++ recursion numbers catalan


    【解决方案1】:

    您超出了这些变量类型允许您存储的最大大小。

    long long 类型是您的最佳选择。

    您可以在这里查看不同类型整数的最大值:http://www.cplusplus.com/reference/climits/

    【讨论】:

    【解决方案2】:

    使用“unsigned long long”代替“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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多