微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

大数计算_乘法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐