[算法设计与分析]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] << " ";
        }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值