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

一、分析

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

 

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

1    2    3

x    1    2

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

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;
}


三、运行结果






作者:山丘儿
转载请标明出处,谢谢。原文地址: http://blog.csdn.net/s634772208/article/details/46505949
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值