现在的位置: 首页 > 综合 > 正文

大数计算_乘法

2013年06月18日 ⁄ 综合 ⁄ 共 1204字 ⁄ 字号 评论关闭
/*limit:a、b>0*/
#include<iostream>
using namespace std;
#include<string>

string add(string x,string y)
{
	string sum;
	int index_x=x.size()-1,index_y=y.size()-1;
		int num=0,tmp=0;
	    while(index_x>=0&&index_y>=0){
		    int num_x=x[index_x]-48,
		 	    num_y=y[index_y]-48;
		        num=num_x+num_y+tmp;
		    string temp;
		    if(num>=10)tmp=num/10;
			else tmp=0;
		    temp+=(num%10+48);
		    sum.insert(0,temp);
		    index_x--;index_y--;
	    }
		if(tmp&&index_x<0&&index_y<0){string temp;temp+=(tmp+48);sum.insert(0,temp);}
		else{
	    while(index_x>=0){
		   string temp;
		   int num=x[index_x]-48+tmp;
		   if(num>=10)tmp=num/10;
		   else tmp=0;
		   temp+=(num%10+48);
		   sum.insert(0,temp);
		   index_x--;
	    }
	    while(index_y>=0){
		   string temp;
		   int num=y[index_y]-48+tmp;
		   if(num>=10)tmp=num/10;
		   else tmp=0;
		   temp+=(num%10+48);
		   sum.insert(0,temp);
		   index_y--;
	    }
		if(tmp){string temp;temp+=(tmp+48);sum.insert(0,temp);}
		}
	return sum;
}

string mul(string a,string b)
{
	int len_b=b.size();
	string sum;
	int mark=1;
	while(len_b>0){
		len_b--;
		int len_a=a.size();
		int k=1*mark;
		mark*=10;
		string pre;
		while(len_a>0){
			int temp=(a[--len_a]-48)*(b[len_b]-48);
			string post;
			if(temp/10!=0){post+=temp/10+48;post+=temp%10+48;}
			else post+=temp+48;
			int counter=k;
			k*=10;
			while(counter>1){
				post+='0';
				counter/=10;
			}
			pre=add(pre,post);
		}
		sum=add(sum,pre);
	}
	return sum;
}

void main()
{
	string a,b;
	while(cin>>a>>b)
		cout<<mul(a,b)<<endl;
}

抱歉!评论已关闭.