What is wrong with my code ?
Am i using a wrong algo ?
/*1818.cpp*/
#include<iostream>
#include<string>
#include<string.h>
#define MAXN 2000
#define MAXNCHAR 4
using namespace std;
string sum(const string &a,const string &b)
{
string res="";
unsigned carry=0,
nA=a.size(),
nB=b.size();
while(nA>0 && nB>0)
{
res.insert(res.begin(),(a[nA-1]-'0'+b[nB-1]-'0'+carry)%10+'0');
carry=(a[nA-1]-'0'+b[nB-1]-'0'+carry)/10;
nA--;
nB--;
}
while(nA>0)
{
res.insert(res.begin(),(a[nA-1]-'0'+carry)%10+'0');
carry=(a[nA-1]-'0'+carry)/10;
nA--;
}
while(nB>0)
{
res.insert(res.begin(),(b[nB-1]-'0'+carry)%10+'0');
carry=(b[nB-1]-'0'+carry)/10;
nB--;
}
if(carry>0)
res.insert(res.begin(),carry+'0');
return res;
}
string mult1(const string &a,char b)
{
string res="";
unsigned i,nA=a.size(),
carry=0;
if(b=='0')
{
res="0";
return res;
}
for(i=0;i<nA;i++)
{
res.insert(res.begin(),((a[nA-1-i]-'0')*(b-'0')+carry)%10+'0');
carry=((a[nA-1-i]-'0')*(b-'0')+carry)/10;
}
while(carry>0)
{
res.insert(res.begin(),carry%10+'0');
carry/=10;
}
return res;
}
string mult(const string &a,const string &b)
{
unsigned i,j,nB=b.size();
string tmp,res="0";
for(i=0;i<nB;i++)
{
tmp=mult1(a,b[nB-1-i]);
for(j=0;j<i;j++)
tmp.insert(tmp.end(),'0');
res=sum(res,tmp);
}
return res;
}
string x,arr[MAXN];
char l=1;
unsigned n;
void read()
{
unsigned i;
char nChar[MAXNCHAR+1];
cin>>n;
for(i=0;i<n;i++)
{
cin>>arr[i];
l=l && arr[i]=="0";
}
sprintf(nChar,"%u",n);
x.assign(nChar);
}
string solve()
{
string res;
unsigned i;
if(l==0)
{
res=arr[n-1];
for(i=1;i<n;i++)
{
res=mult(res,x);
res=sum(res,arr[n-1-i]);
}
return res;
}
res=x;
for(i=1;i<n;i++)
res=mult(res,x);
return res;
}
void write()
{
cout<<solve()<<endl;
}
int main()
{
read();
write();
return 0;
}
Edited by author 08.02.2011 01:51
Edited by author 08.02.2011 01:52
Edited by author 10.02.2011 16:32