高精度四則運算(待改進)
阿新 • • 發佈:2019-02-13
struct bign { int len,s[20005],res[20005]; bign () { memset(s,0,sizeof(s)); memset(res,0,sizeof(res)); len=1; } void read(char ss[]) { len=strlen(ss); int cnt=0; while(ss[cnt]=='0') cnt++; len-=cnt; for(int i=0;i<len;i++) s[i]=ss[i+cnt]-'0'; for(int i=0;i<len;i++) res[i]=s[len-i-1]; } void out() { for(int i=0;i<len;i++) printf("%d",s[i]); } friend bool operator <(bign a,bign b) { if(a.len<b.len) return true; if(a.len>b.len) return false; int i=0; while(i<a.len) { if(a.s[i]>b.s[i]) return false; if(a.s[i]<b.s[i]) return true; i++; } return false; } friend bool operator >(bign a,bign b) { return b<a; } friend bool operator <=(bign a,bign b) { return !(a>b); } friend bool operator >=(bign a,bign b) { return !(a<b); } friend bool operator ==(bign a,bign b) { return (a>=b) && (a<=b); } friend bign operator +(bign a,bign b) { bign c; c.len=max(a.len,b.len); int ok=0; for(int i=0;i<c.len;i++) { c.res[i]=a.res[i]+b.res[i]+ok; if(c.res[i]>=10) { ok=1; c.res[i]=c.res[i]%10; } else ok=0; } if(ok) { c.len++; c.res[c.len-1]=1; } for(int i=0;i<c.len;i++) c.s[i]=c.res[c.len-i-1]; return c; } friend bign operator -(bign a,bign b) { bign c; c.len=max(a.len,b.len); int ok=0; for(int i=0;i<c.len;i++) { a.res[i]-=ok; ok=0; if(a.res[i]<b.res[i]) { ok=1; c.res[i]=a.res[i]+10-b.res[i]; } else c.res[i]=a.res[i]-b.res[i]; } for(int i=c.len-1;i>=0;i--) { if(c.res[i]==0) c.len--; else break; } for(int i=0;i<c.len;i++) c.s[i]=c.res[c.len-i-1]; return c; } friend bign operator *(bign a,bign b) { bign c; for(int i=0;i<a.len;i++) { bign d; int ok=0; d.len=b.len+i; for(int j=0;j<b.len;j++) { d.res[i+j]=a.res[i]*b.res[j]+ok; ok=d.res[i+j]/10; d.res[i+j]%=10; } if(ok>0) { d.len++; d.res[d.len-1]=ok; } for(int j=0;j<d.len;j++) d.s[j]=d.res[d.len-j-1]; c=c+d; } return c; } friend bign operator /(bign a,bign b) { bign c; if(a<b) return c; else if(a==b) c.s[0]=c.res[0]=1; else { c.len=1; bign ten; ten.s[0]=1;ten.res[1]=1;ten.len=2; //定義一個10方便運算 while(a>b&&b*ten<a) { b=b*ten; c.len++; } for(int i=0;i<c.len;i++) { c.s[i]=0; while(a>b) { a=a-b; c.s[i]++; } for(int j=0;j<b.len;j++) b.res[j]=b.res[j+1]; b.len--; c.res[c.len-i-1]=c.s[i]; } } return c; } };