1. 程式人生 > >連結串列實現大數類階乘

連結串列實現大數類階乘

連結串列實現大數階乘

題目

大數運算——計算n的階乘 (n≥20)。

基本要求

(1)資料的表示和儲存:
①累積運算的中間結果和最終的計算結果的資料型別要求是整型——這是問題本身的要求。
②試設計合適的儲存結構,要求每個元素或結點最多儲存資料的3位數值。
(2)資料的操作及其實現:
基於設計的儲存結構實現乘法操作,要求從鍵盤上輸入n值;在螢幕上顯示最終計算結果。

思路

建立大數類(其實好像想麻煩了),不過面向物件的方法還挺好寫的,過載乘法,這裡我搞麻煩了,一開始過載了大數乘法,其實弄一個大數乘整數就行了,然後其他的比較簡單了,主要是細節,一直改Bug,終於好了。

1)類定義

class Biginteger {
    Node *first;
    int length;
public:
    Biginteger() {
        first = new Node(0);
    }
    Node *GetHead() {
        return first;
    }
    friend ostream&operator<<(ostream &, const Biginteger&);
    friend istream&operator>>(istream &, Biginteger&);
    Biginteger operator+(int);
    Biginteger operator*(Biginteger &);
    Biginteger operator*(int);
    bool operator==(Biginteger&);
    Biginteger Cal_Mul(Biginteger&);
    Biginteger Cal_Mul(int);
    void Delete();
};

2)類實現(只有關鍵部分)

Biginteger Biginteger::operator*(int R)
{
    Biginteger C;
    Node *pc = C.first, *pa = GetHead()->link;
    pc->insertAfter(0);
    int t = R % 10;
    int temp;
    int n;
    int num = 0;
    while (R) {
        pa = GetHead()->link;
        pc = C.GetHead();
        n = 0;
        while (n < num) {
            pc = pc->link;
            n++;
        }
        num++;
        while (pa != NULL) {
            temp = t * pa->value;
            if (pc->link == NULL) {
                pc->insertAfter(temp % 10);
            }
            else {
                pc->link->value += (temp % 10);
            }
            pc = pc->link;
            if (pc->value >= 10) {
                if (pc->link == NULL) {
                    pc->insertAfter((pc->value) / 10);
                }
                else {
                    pc->link->value += ((pc->value) / 10);
                }
                pc->value = (pc->value) % 10;
            }
            if (temp >= 10) {
                if (pc->link == NULL) {
                    pc->insertAfter(temp / 10);
                }
                else {
                    pc->link->value += (temp / 10);
                }
                if (pc->link->value >= 10) {
                    if (pc->link->link == NULL) {
                        pc->link->insertAfter((pc->link->value) / 10);
                    }
                    else {
                        pc->link->link->value += ((pc->link->value) / 10);
                    }
                    pc->link->value = (pc->link->value) % 10;
                }
            }

            pa = pa->link;
        }
        R /= 10;
        t = R % 10;
        if (pc->link == NULL && pa != NULL)
            pc = pc->insertAfter(0);
        else    pc = pc->link;
    }
    return C;
}

3)階乘實現

Biginteger Biginteger::Cal_Mul(int R) {
    Biginteger ans;
    ans.first->insertAfter(1);
    if (R == 1) {
        return ans;
    }
    for (int i(2); i <= R; i++) {
        ans = ans * i;
    }
    return ans;
}

後記

依舊沒有註釋,提供一種思路吧,其實我覺得我寫的很糙,太長了,而且一個結點只存了一個數字,有點浪費,不過親測可用,思路差不多的可以參考一下。
2018/11/14 23: 31:14