大数乘法——逐位与移位算法

在题目中,总会出现要求用很大很大的数来进行运算,这时候就涉及大数运算,这次首先介绍一下大数乘法的处理。代码经过优化,非常简便

逐位相乘处理进位法

乘积是逐位相乘,也就是aibj ,结果加入到积c的第i+j位,最后处理进位即可

举例:

A=13,B=19
a=(3,1),b=(9,1)
c=(3 9,3 1+1 9,1 1)=(27,12,1)=(7,14,1)=(7,4,2)
C=247

因此,大题思路是:

  • 转换并反转,字符串转换为数字并将字序反转;
  • 逐位相乘,并处理进位,结果存放在result[i+j]中;
  • 消除多余的0;
  • 转换并反转,将计算结果转换为字符串并反转。

我将代码优化,尽可能减少代码的书写

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

void multply(string &a, string &b)
{
    string result(a.size()+b.size(),'0');//初始化结果数组
    unsigned int c = 0;
    for(unsigned int i = 0; i < a.size(); i++)
    {
        unsigned int j;
        for(j = 0; j < b.size(); j++)
        {
            c +=  (result[i+j] - '0') + (a[i] - '0')*(b[j] - '0');
            result[i+j] = (c % 10) + '0';
            c /= 10;
        }
        while(c)
        {
            result[i+j++] += (c % 10);
            c /= 10;
        }
    }
    for(unsigned int i = result.size() - 1; i >= 0; i--)//去掉高位0
    {
        if(result[i] != '0')
        {
            break;
        }
        else
        {
            result.erase(result.begin() + i,result.end());//截断后面全0
        }
    }
    //cout<<result<<endl;
    reverse(result.begin(),result.end());
    cout<<result<<endl;
}

main()
{
    string a,b;
    cin>>a>>b;
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    multply(a,b);
}

运行结果:

这里写图片描述

这里写图片描述

移位进位法

举例:
这里写图片描述

因此,大体思路是:

  • 转换并反转,字符串转换为数字并将字序反转;
  • 移位相乘,并处理进位,结果存放在result[i]中;
  • 消除多余的0;
  • 转换并反转,将计算结果转换为字符串并反转。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void multply(string a, string b)
{
    string result(a.size()+b.size(),'0');//初始化结果数组
    unsigned int c = 0, tmp_i = 0, tmp_j = 0;
    for(unsigned int i = 0; i!=a.size(); i++, tmp_j++)
    {
        tmp_i = tmp_j;  //在每次计算时,结果存储的位需要增加
        unsigned int j;
        for(j = 0; j < b.size(); j++)
        {
            c += (result[tmp_i] - '0') + (a[i] - '0')*(b[j] - '0');
            result[tmp_i++] = (c % 10) + '0';
            c /= 10;
        }
        while(c)//处理最后进位
        {
            result[tmp_i++] = (c % 10) + '0';
            c /= 10;
        }
    }
    for(unsigned int i = result.size() - 1; i >= 0; i--)
    {
        if(result[i] != '0')
        {
            break;
        }
        else
        {
            result.erase(result.begin() + i,result.end());//截断后面全0
        }
    }
    //cout<<result<<endl;
    reverse(result.begin(),result.end());
    cout<<result<<endl;
}

int main()
{
    string a,b;
    cin>>a>>b;
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    multply(a,b);
    return 0;
}

运行结果

这里写图片描述
这里写图片描述

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