Catalan數的解法

來源:互聯網
上載者:User

Catalan數的解法

Catalan數的組合公式為 Cn=C(2n,n) / (n+1);

此數的遞迴公式為  h(n ) = h(n-1)*(4*n-2) / (n+1)

 小數解

對於50以下的小數解來說,使用數組就可以完成,代碼如下:

#include<iostream>

using namespace std;

int main()

{

     long long  int a[101][101],i,j,n;

    for (i=0; i<101; i++)    //利用數組求 Catalan數

        a[i][0] = 1;

    for (i=1; i<101; i++)                    

    {

        for (j=1; j<=i; j++)   

            a[i][j] = a[i][j-1] + a[i-1][j];   

    }

    while (cin>>n)   

    {     

        cout<<a[n][n]<<endl;

    }

    return 0;

}

 大數解

對於大數來說,就應該使用下面的大數演算法。

使用的公式為:h(n)  = h(n-1)*(4*n-2)/n+1;

#include<iostream>

using namespace std;

#define MAX 100

#define BASE 10000

void multiply(int a[],int Max,int b)  //大數乘法

{

    int i,array=0;

    for (i=Max-1; i>=0; i--)   

    {

        array+=b*a[i];

        a[i] = array%BASE;

        array /= BASE;   

    }

}

 

void divide(int a[], int Max, int b)  //大數除法

{

    int i,div=0;

    for (i=0;i<Max; i++)   

    {

        div = div*BASE + a[i];

        a[i] = div / b;

        div %= b;

    }

}

int main()

{

    int a[101][MAX],i,j,n;

    memset(a[1],0,MAX*sizeof(int));

    for (i=2,a[1][MAX-1]=1; i<101; i++)

    {

        memcpy(a[i],a[i-1],MAX*sizeof(int));      //h[I] = h[i-1];  

        multiply(a[i],MAX,4*i-2);               //h[i] *= (4*i-2);

        divide(a[i],MAX,i+1);                  //h[i] /= (i+1);

    }

    while (cin>>n)   

    {

        for (i=0; i<MAX && a[n][i]==0; i++);  //去掉數組前為0的數字。

        cout<<a[n][i++];             //輸出第一個非0數

        for (; i<MAX; i++)   

            printf("%04d",a[n][i]);       //輸出後面的數,並每位都保持5位長度

        cout<<endl;

    }

    return 0;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.