设计大数类.可以实现大数的基本加减乘除运算.用C++语言 来编写

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/11 14:25:23
设计大数类.可以实现大数的基本加减乘除运算.用C++语言 来编写

设计大数类.可以实现大数的基本加减乘除运算.用C++语言 来编写
设计大数类.可以实现大数的基本加减乘除运算.
用C++语言 来编写

设计大数类.可以实现大数的基本加减乘除运算.用C++语言 来编写
//楼主还是留个邮箱吧,直接发源代码给你.
//加减乘除 取模 幂,大小判断 赋值 重载.
#include
#include
#include
using namespace std;
class BigNum;
istream& operator>>(istream&, BigNum&);
ostream& operator(istream&, BigNum&);
friend ostream& operator(const int & t)const;

};
//////输入 .
istream& operator>>(istream & in, BigNum & b)
{
char ch[MAXSIZE*4];
int i = -1;
memset(b.a,0,sizeof(b.a));
in>>ch;
int l=strlen(ch);
int count=0,sum=0;
for(i=l-1;i>=0;)
{
sum = 0;
int t=1;
for(int j=0;j=0;j++,i--,t*=10)
{
sum+=(ch[i]-'0')*t;
}
b.a[count]=sum;
count++;
}
b.len =count++;
return in;

}
/////输出 .
ostream& operatorT)
{
t1=*this;
t2=T;
flag=0;
}
else
{
t1=T;
t2=*this;
flag=1;
}
big=t1.len;
for(i = 0 ; i < big ; i++)
{
if(t1.a[i] < t2.a[i])
{
j = i + 1;
while(t1.a[j] == 0) j++;
t1.a[j--]--;
while(j > i) t1.a[j--] += MAXN;
t1.a[i] += MAXN + 1 - t2.a[i];
}
else t1.a[i] -= t2.a[i];
}
t1.len = big;
while(t1.a[len - 1] == 0 && t1.len > 1)
{
t1.len--;
big--;
}
if(flag)t1.a[big-1]=0-t1.a[big-1];
return t1;
}
////大数与大数的乘法.
BigNum BigNum::operator*(const BigNum & T) const
{
BigNum ret;
int i,j,up;
int temp,temp1;
for(i = 0 ; i < len ; i++)
{
up = 0;
for(j = 0 ; j < T.len ; j++)
{
temp = a[i] * T.a[j] + ret.a[i + j] + up;
if(temp > MAXN)
{
temp1 = temp - temp / (MAXN + 1) * (MAXN + 1);
up = temp / (MAXN + 1);
ret.a[i + j] = temp1;
}
else
{
up = 0;
ret.a[i + j] = temp;
}
}
if(up != 0)
ret.a[i + j] = up;
}
ret.len = i + j;
while(ret.a[ret.len - 1] == 0 && ret.len > 1) ret.len--;
return ret;
}
////大数与int的除法.
BigNum BigNum::operator/(const int & b) const
{
BigNum ret;
int i,down = 0;
for(i = len - 1 ; i >= 0 ; i--)
{
ret.a[i] = (a[i] + down * (MAXN + 1)) / b;
down = a[i] + down * (MAXN + 1) - ret.a[i] * b;
}
ret.len = len;
while(ret.a[ret.len - 1] == 0 && ret.len > 1) ret.len--;
return ret;
}
////大数与int的取余.
int BigNum::operator %(const int & b) const
{
int i,d=0;
for (i = len-1; i>=0; i--)
{
d = ((d * (MAXN+1))% b + a[i])% b;
}
return d;
}
////大数幂.
BigNum BigNum::operator^(const int & n) const
{
BigNum t,ret(1);
int i;
if(n1)
{
t=*this;
for( i=1;i T.a[ln]) return true;
else return false;
}
else return false;
}
//大数相等判断.
bool BigNum::operator==(const BigNum & T) const
{
int ln;
if(len != T.len) return false;
else
{
ln = len - 1;
while(a[ln] == T.a[ln] && ln-- );
if(ln < 0) return true;
else return false;
}
}
//大数与int 大小判断.
bool BigNum::operator >(const int & t) const
{
BigNum b(t);
return *this>b;
}
//大数 与int相等判断.
bool BigNum::operator==(const int & t) const
{
BigNum b(t);
return *this==b;
}
//
int main()
{
int t;
int i;
BigNum a,b,c;
cin>>t;
for(i=1;i>a>>b;
printf("Case %d:\n",i);
c=a+b;
cout