开发者

Long numbers. Division

world! I have a problem. Today I tried to create a code, which finds Catalan number. But in my program can be long numbers. I found numerator and denominator. But i can't div long numbers! Also, only standard libraries was must use in this program. Help me please. This is my code

#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    const int base = 1000*1000*1000;
    vector <int> a, b;
    int n, carry = 0;
    cin>>n;
    a.push_back(n);                     
    for (int ii=n+2; ii!=(2*n)+1;++ii) { 
        carry = 0;                      
        for (size_t i=0; i<a.size() || carry; ++i) {
            if (i == a.size())
                a.push_back (0);
            long long cur = carry + a[i] * 1ll * ii;
            a[i] = int (cur % base);
            carry = int (cur / base);
        }
    }
    while (a.size() > 1 && a.back() == 0) a.pop_back();

    b.push_back(n);                
    for (int ii=1; ii!=n+1;++ii) {
        c开发者_高级运维arry = 0;
        for (size_t i=0; i<b.size() || carry; ++i) {
            if (i == b.size())
                b.push_back (0);
            long long cur = carry + b[i] * 1ll * ii;
            b[i] = int (cur % base);
            carry = int (cur / base);
        }
    }
    while (b.size() > 1 && b.back() == 0) b.pop_back();

    cout<<(a.empty() ? 0 : a.back());
    for (int i=(int)a.size()-2; i>=0; --i) cout<<(a[i]);

    cout<<"   ";

    cout<<(b.empty() ? 0 : b.back());
    for (int i=(int)b.size()-2; i>=0; --i) cout<<(b[i]);
    //system("PAUSE");
    cout<<endl;
    return 0;
}

P.S. Sorry for my bad english =)


You don't have to calculate (2n)! in order to calculate (2n)!/(n!(n+1)!)), because you can use the recurrence relation given in this link:

C(0)=1
C(n)=(4n-2)C(n-1)/(n+1)

This gives you the first 15 terms using just 32-bit arithmetic. And you can generate up to 16384 terms just by using multiplication and division of an arbitrary-length integer by a 16-bit integer. This is much easier than general arbitrary-precision arithmetic, and might well be set as a homework task.


It will be very difficult implement division in your representation of long numbers, but it is real. In my opinion, the simplest method is Long_division.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜