任意大的自然数相乘,谁愿意完成其他工作?
#include <stdio.h>
#include <string.h>
class NUMBER{
char *n;
public:
NUMBER(char *n);
NUMBER(NUMBER const &a);
~NUMBER();
NUMBER operator+(const NUMBER &a) const;
NUMBER operator*(const NUMBER &a) const;
NUMBER operator++(int);
NUMBER & operator=(const NUMBER &a);
NUMBER &operator++();
operator const char *()const;
};
NUMBER &NUMBER::operator++(){
*this=*this+"1";
return *this;
}
NUMBER NUMBER::operator++(int){
NUMBER r(*this);
*this=*this+"1";
return r;
}
NUMBER::NUMBER(char *n){
if(NUMBER::n=new char[strlen(n)+1]) strcpy(NUMBER::n, n);
}
NUMBER::NUMBER(const NUMBER &a){
if(n=new char[strlen(a.n)+1]) strcpy(n, a.n);
}
NUMBER::~NUMBER(){
if(n) { delete n; n=0; }
}
NUMBER &NUMBER::operator=(const NUMBER &a){
delete n;
if(n=new char[strlen(a.n)+1]) strcpy(n, a.n);
return *this;
}
NUMBER NUMBER::operator+(const NUMBER &a) const{
int m, c=0, p=strlen(n), q=strlen(a.n);
if(p>q) m=p; else m=q; m+=2;
char *t=new char[m]; t[--m]=0;
while (p>0 && q>0){
c=c+n[--p]+a.n[--q]-2*'0';
t[--m]=((c>=10)?c-10: c)+'0';
c=(c>=10)? 1: 0;
}
while (p>0){
c=c+n[--p]-'0';
t[--m]=((c>=10)?c-10: c)+'0';
c=(c>=10)?1: 0;
}
while (q>0){
c=c+a.n[--q]-'0';
t[--m]=((c>=10)?c-10: c)+'0';
c=(c>=10)?1: 0;
}
if(c>0) {t[--m]='1'; }
NUMBER x(t+m);
delete t;
return x;
}
NUMBER NUMBER::operator*(const NUMBER &a) const{
int v,w, c, p=strlen(n), q=strlen(a.n);
NUMBER r("");
NUMBER b((p>q)?n:a.n);
NUMBER m((p>q)?a.n:n);
for(v=0, w=((p>q)?q:p); v<w; v++){
char *t=new char[strlen(r.n)+2];
r=strcat(strcpy(t, r.n), "0");
delete t;
for(c=m[v]-'0'; c>0; c--) r=r+b;
}
if (strlen(r)==0) return NUMBER("0");
return r;
}
NUMBER::operator const char *() const{
return n;
}
void main(){
NUMBER x("12345678924124232142142341242133324345342434235190909034");
NUMBER y("9876543213453665575673653653343453434097857623432332324");
++x;
printf("%s\n", x);
++ ++x;
printf("%s\n", x);
printf(x*y);
}