一、分析

整数的数值超过计算机硬件所能表示的最大值时,那么我们只能借助软件的方法来实现大整数的乘法了。

 

我们可以使用字符串来模拟大整数的乘法,算法的思想就是使用我们在小学时学过的乘法,一位位相乘,最后计算出结果。如下:

1    2    3

x    1  

------------------------

2 4 6

1 2 3

------------------------

1 4 7 6

 

为了模拟乘法过程,我们需要使用两个字符串变量,一个保存每一步乘积结果,另一个保存最终的结果。

 

时间复杂度:算法时间总要消耗在两层循环中,故时间复杂度为O(n^2)。

 

二、代码实现

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

using namespace std;


//求两个大数的乘积(两数均为正数)
string GetProductOfTwoBigNum( string strNumLeft, string strNumRight )
{

//使用小学所学方法,计算两个大数乘积
///

if ( strNumRight.empty() && strNumRight.empty() )
{
return string("0");
}

//转换为数字
for( string::size_type i = 0; i < strNumLeft.size(); ++i )
{
strNumLeft[i] -= '0';
}
for( string::size_type i = 0; i < strNumRight.size(); ++i )
{
strNumRight[i] -= '0';
}


string::size_type nMaxBits = strNumLeft.size() + strNumRight.size() + 1;//最大位数,多增加一位,便于编码
string strProduct( nMaxBits, NULL );//保存每步乘积累加之和
char szTemp = NULL;//每位乘积,辅助变量
char szCarrayTemp = NULL;//进位信息

for( int i = strNumRight.size() - 1; i >= 0; --i )
{
string strProductStep( nMaxBits, NULL );//保存每步之和
int k = strNumRight.size() - i - 1;
for( int j = strNumLeft.size() - 1; j >= 0; --j )
{
szTemp = ( strNumRight[i] * strNumLeft[j] + strProductStep[k] ) % 10;
szCarrayTemp = ( strNumRight[i] * strNumLeft[j] + strProductStep[k] ) / 10;

strProductStep[k] = szTemp;
strProductStep[++k] += szCarrayTemp;
}

//将这一步结果累加strProduct中
for( string::size_type m = 0; m < nMaxBits - 1; ++m )
{
szTemp = ( strProductStep[m] + strProduct[m] ) % 10;
szCarrayTemp = ( strProductStep[m] + strProduct[m] ) / 10;

strProduct[m] = szTemp;
strProduct[m+1] += szCarrayTemp;
}
}

//返回遍历strProduct,从而取出计算的结果
string strResult;
int k = nMaxBits - 1;
while( k >= 0 && strProduct[k] == NULL )
{
--k;
}
for( ; k >= 0; --k )
{
strResult.push_back( strProduct[k] + '0');//转换为字符
}

if ( strResult.empty() )
{
strResult.push_back( '0' );
}

return strResult;
}


int main()
{
string strNumLeft;
string strNumRight;


cout << "输入两个乘数:";
while( cin >> strNumLeft >> strNumRight )
{
string strResult = GetProductOfTwoBigNum( strNumLeft, strNumRight );
cout << "两数之积:" << strResult << endl;
cout << "-------------------------------------------------" << endl;
cout << "输入两个乘数:";
}

return 0;
}



三、运行结果



大整数乘法(简单模拟乘法过程)_#include







作者:山丘儿