Wednesday, January 6, 2010

Multiplication of two large numbers

#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1,s2;
int i,j,k,a,c,n;
cin>>n;
while(n--)
{
cin>>s1;
cin>>s2;
int A[21000]={0},B[21000]={0};
if(s1[0]-48==0 || s2[0]-48==0)
{
cout<<"0"<<endl;
}
else
{
for(i=s1.length()-1; i>=0; i--)
{
c=0;
//zero padding.
for(k=0;k<s1.length()-1-i;k++)
{
B[k]=0;
}
for(j=s2.length()-1; j>=0; j--)
{
int a=(s1[i]-48)*(s2[j]-48)+c;
if(a>9)
{
B[k]=a%10;
c=a/10;
k++;
}
else
{
B[k]=a%10;
c=0;
k++;
}
}
if(c>0)
{
B[k]=c;
c=0;
k++;
}
for(j=0;j<k;j++)
{
int a=A[j]+B[j]+c;
if(a>9)
{
A[j]=a%10;
c=a/10;
}
else
{
A[j]=a%10;
c=0;
}
}
}
for(i=k-1;i>=0;i--)
{
cout<<A[i];
}
cout<<endl;
fflush(stdin);
}
}
return 0;
}
Enter the first number: 9999999
Enter the second number: 999
The product is:
9989999001

No comments:

Post a Comment