[算法設計與分析]3.2.4大整數存儲及運算(高精度*長整數+n!)

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<math.h>

using namespace std;

void StoreGreatNumber();
void Multiply();

int main ()
{
    StoreGreatNumber();
    Multiply();
}

void StoreGreatNumber()
{
    long b, d;
    int a[256];
    char s1[256] = "234763";
    long c = 234;
    int n = strlen(s1);
    d = 0;//d代表進位
    for(int i = 0, j = n - 1; i < n; i++, j--)
    {
        b = (s1[j] - 48) * c + d;//將高精度數據的每一位分別與自然數相乘再加上進位
        a[i] = b % 10;
        d = b / 10;
    }
    while(d)//因爲d代表的數可能極大 因此不能直接存儲到相應的爲中 要一位一位的存
    {
        a[n] = d % 10;
        d /= 10;
        n++;
    }
    for(int i = n - 1; i >= 0; i--)
        cout << a[i];
    cout << endl << endl;
}

void Multiply()
{
    long a[256];//數組a中存儲每次累乘之後的結果, 因爲爲long 因此每個元素存儲6位
    long b;//存儲中間結果
    long d;//存儲超過6位之後的進位
    long n = 100;//求n的階乘
    int r, i, j;

    int m = log(n) * n / 6 + 2;//對n!的位數的粗略估計

    a[1] = 1;
    for(int i = 2; i <= m; i++)
        a[i] = 0;
    d = 0;
    for(i = 2; i <= n; i++)//i代表要累乘的數據
    {
        for(j = 1; j <= m; j++)//j代表當前累乘結果的數組下標
        {
            b = a[j] * i + d;
            a[j] = b % 1000000;
            d = b / 1000000;//若是沒有超出6位 則d始終爲0 a數組始終只有a[1]不爲0
        }
        if(d != 0)
            a[j] = d;
    }
    for(i = m; i >= 1; i--)
    {
        if(a[i] == 0)
        continue;
        else
        {
            r = i;
            break;
        }
    }
        cout << n << "!=";
        cout << a[r] << " ";
        for(i = r - 1; i >= 1; i--)
        {
            if(a[i] > 99999)
            {
                cout << a[i] << " ";
                continue;
            }
            if(a[i] > 9999)
            {
                cout << "0" << a[i] << " ";
                continue;
            }
            if(a[i] > 999)
            {
                cout << "00" << a[i] << " ";
                continue;
            }
            if(a[i] > 99)
            {
                cout << "000" << a[i] << " ";
                continue;
            }
            if(a[i] > 9)
            {
                cout <<"0000" << a[i] << " ";
                continue;
            }
            cout <<"00000" << a[i] << " ";
        }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章