在题目中,总会出现要求用很大很大的数来进行运算,这时候就涉及大数运算,这次首先介绍一下大数乘法的处理。代码经过优化,非常简便
逐位相乘处理进位法
乘积是逐位相乘,也就是
举例:
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;
}
运行结果