您的位置:首页 > 编程语言 > C语言/C++

一个简单的C++大数类(希望可以得到各种建议)

2013-04-20 12:22 330 查看
暂时只有整形高精加减乘,希望大家可以指出不足之处。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
const int MAXN=4000;
struct BIGNUM {
int sgn,len,s[MAXN];
BIGNUM () {memset(s,0,sizeof(s)); len=1; sgn=1; }
BIGNUM operator = (const char* num) {
if (*num=='-'||*num=='+') {
sgn=*num=='+'?1:-1;
++num;
}
len=strlen(num);
for (int i=0;i<len;++i) s[i]=num[len-i-1]-'0';
return *this;
}
BIGNUM operator = (const int num) {
char a[MAXN];
sprintf(a,"%d",num);
*this = a;
return *this;
}
BIGNUM (int num) { *this=num; }
BIGNUM (const char * num) { *this=num; }
BIGNUM (const BIGNUM & x) {*this = x; }
bool operator < (const BIGNUM & x) const {
if (sgn!=x.sgn) return sgn<x.sgn;
if (len != x.len) return len<x.len;
for (int i=len-1;i>=0;--i) {
if (s[i] != x.s[i]) return s[i]<x.s[i];
}
return false;
}
bool operator > (const BIGNUM & x) const { return x<*this; }
bool operator <= (const BIGNUM & x) const { return !(x<*this); }
bool operator >= (const BIGNUM & x) const { return !(*this<x); }
bool operator == (const BIGNUM & x) const { return !(x<*this||*this<x); }
bool operator != (const BIGNUM & x) const { return x<*this||*this<x; }
BIGNUM operator + (const BIGNUM & a) const {
BIGNUM c;
c.len=max(len,a.len)+1;
if (sgn==a.sgn) {
c.sgn=sgn;
for (int i=0;i<c.len;++i) {
c.s[i]+=s[i]+a.s[i];
c.s[i+1]=c.s[i]/10;
c.s[i]=c.s[i]%10;
}
} else {
BIGNUM t1=*this,t2=a;
t1.sgn=1; t2.sgn=1;
if (t1<t2) {
c.sgn=a.sgn;
BIGNUM tmp=t1;
t1=t2;
t2=tmp;
} else c.sgn=sgn;
for (int i=0;i<c.len;++i){
c.s[i]+=t1.s[i]-t2.s[i];
if (c.s[i]<0) {
c.s[i]+=10;
--c.s[i+1];
}
}
}
while (c.s[c.len-1]==0&&c.len>1) --c.len;
if (c.s[0]==0&&c.len==1) c.sgn=1;
return c;
}
BIGNUM operator += (const BIGNUM & a) {
*this = *this+a;
return *this;
}
BIGNUM operator - (const BIGNUM & a) const {
BIGNUM c=a;
c.sgn=-c.sgn;
c+=*this;
return c;
}
BIGNUM operator -= (const BIGNUM & a) {
*this = *this-a;
return *this;
}
BIGNUM operator * (const BIGNUM & x) const {
BIGNUM c;
c.sgn=sgn*x.sgn;
c.len=len+x.len;
for (int i=0;i<len;++i) {
for (int j=0;j<x.len;++j) {
c.s[i+j]+=s[i]*x.s[j];
c.s[i+j+1]+=c.s[i+j]/10;
c.s[i+j]%=10;
}
}
while (c.s[c.len-1]==0&&c.len>1) --c.len;
if (c.s[0]==0&&c.len==1) c.sgn=1;
return c;
}
BIGNUM operator *= (const BIGNUM & x) {
*this = *this*x;
return *this;
}

};

istream& operator >> (istream &in,BIGNUM &x) {
char num[MAXN];
in>>num;
x=num;
return in;
}

ostream& operator << (ostream &out,const BIGNUM& x) {
if (x.sgn==-1) cout<<'-';
for (int i=x.len-1;i>=0;--i)
cout<<x.s[i];
return out;
}

BIGNUM f[5001];

int main()
{
BIGNUM a,b;
cin>>a>>b;
cout<<a*b<<endl;
cout<<a+b<<endl;
cout<<a-b<<endl;
return 0;
}
转载请注明 蝼蚁在奔跑/article/11374640.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐