
Untitled
By: a guest on
Jun 17th, 2012 | syntax:
None | size: 3.42 KB | hits: 21 | expires: Never
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
class BigInteger
{
char *str;
int len;
public:
BigInteger (char a[ ]) /* Constructor that Dynamically allocates memory to hold the number and
initializes the number with a[ ] and sets the length. */
{
len=strlen(a);
str=new char [len+1];
strcpy(str,a);
}
BigInteger( ) /*Default constructor that creates a big integer equivalent to zero. */
{
len=1;
str=new char[len+1];
(*str)='0';
}
BigInteger(const BigInteger &ob)
{
len=strlen(ob.str);
str=new char[len+1];
strcpy(str,ob.str);
}
//assignment operator overloading
BigInteger &operator=(BigInteger ob)
{
if(strlen(ob.str)>len)
{
/*if(str) */delete [] str;
len=strlen(ob.str);
str=new char[len+1];
strcpy(str,ob.str);
}
else
{
len=strlen(ob.str);
strcpy(str,ob.str);
}
return *this;
}
~BigInteger ( ) /*Destructor that frees memory. */
{
delete [] str;
}
void SetBigInteger(char a[ ] ) /* This function is like the first constructor that the number with a[ ]
and sets the Length. */
{
if(strlen(a)>len)
{
delete [] str;
len=strlen(a);
str=new char[len+1];
strcpy(str,a);
}
else
{
len=strlen(a);
strcpy(str,a);
}
}
BigInteger Multiply(BigInteger n) /* Multiplies big integer n with current object and returns the
result, without affecting the current object. */
{
BigInteger res;
res.len=len+n.len;
res.str=new char[res.len+1];
memset(res.str,'0',res.len);
int i,j,k,carry=0,count=0,cnt,track=res.len-1;
char **arr;
arr=new char*[n.len];
for(i=0;i<n.len;i++)
{
arr[i]=new char [res.len];
}
for(i=n.len-1;i>=0;i--)
{
cnt=count;
track=res.len-1-count;
for(j=res.len-1;cnt>0;cnt--,j--)
{
arr[n.len-i-1][j]='0';
}
for(j=len-1;j>=0;j--)
{
arr[n.len-i-1][track]=(str[j]-'0')*(n.str[i]-'0')+carry;
if((int)arr[n.len-i-1][track]>9)
{
carry=(arr[n.len-i-1][track])/10;
arr[n.len-i-1][track]=(((int)arr[n.len-i-1][track])%10)+'0';
}
else
{
carry=0;
arr[n.len-i-1][track]=(((int)arr[n.len-i-1][track]))+'0';
}
track--;
}
for(j=track;j>=0;j--)
{
arr[n.len-i-1][j]=carry+'0';
if(arr[n.len-i-1][track]>'9')
{
carry=(arr[n.len-i-1][track]-'0')/10;
arr[n.len-i-1][track]=((arr[n.len-i-1][track]-'0')%10)+'0';
}
else carry=0;
}
count++;
}
carry=0;
//final answer
for(i=res.len-1;i>=0;i--)
{
for(j=0;j<n.len;j++)
{
res.str[i]+=arr[j][i]+carry-'0';
carry=0;
}
if(res.str[i]>'9')
{
carry=(res.str[i]-'0')/10;
res.str[i]=((res.str[i]-'0')%10)+'0';
}
else carry=0;
}
res.str[res.len]='\0';
return res;
}
void Show( )/* Prints the big integer on screen. */
{
char *p;
p=str;
while((*p)=='0')
{
p++;
}
cout<<p<<endl;
}
};
int main()
{
char s1[500],s2[500];
BigInteger a,b,res;
while(( scanf("%s%s",s1,s2) )!=EOF)
{
a.SetBigInteger(s1);
b.SetBigInteger(s2);
if(s1[0]=='0' || s2[0]=='0')
{
cout<<"0"<<endl;
}
else
{
res=a.Multiply(b);
res.Show();
}
memset(s1,'\0',500);
memset(s2,'\0',500);
}
return 0;
}