#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
string fill(string a, int n){
while(a.size()<n) a='0'+a;
return a;
}
string add(string a, string b)
{
int m=max(a.size(),b.size());
a=fill(a,m);
b=fill(b,m);
int car=0;
string res;
for(int i=m-1;i>=0;i--){
int z=((a[i]+b[i]-2*'0'+car)%10);
res+=(z+'0');
car=((a[i]+b[i]-2*'0'+car)/10);
}
if(car>0) res+='1';
reverse(res.begin(), res.end());
return res;
}
string mul(string as, string bs){
string sum="0",cs,res;
int k=0;
int car=0;
for(int i=as.size()-1;i>=0;i--){
for(int j=bs.size()-1;j>=0;j--){
int z=((((as[i]-'0')*(bs[j]-'0'))+car)%10);
cs+=(z+'0');
car=((((as[i]-'0')*(bs[j]-'0'))+car)/10);
}
if(car>0) cs+=(car+'0');
car=0;
reverse(cs.begin(),cs.end());
for(int l=0;l<k;l++) cs+="0";
sum=add(sum,cs);
cs.clear();
k++;
}
return sum;
}
bool check_zero(string as){
if(as[0]=='0'){
int cnt=0,i;
for(int i=0;i<as.size();i++){
if(as[i]!='0') return false;
}
return true;
}
else return false;
}
int main()
{
string as,bs,res;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
#endif
while(cin>>as>>bs){
res=mul(as,bs);
if(check_zero(res)==true) printf("0\n");
else cout<<res<<endl;
}
return 0;
}
Friday, November 2, 2012
Big Integer Multiplication in C++
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment