高精度模板

xiaoxiao2021-02-28  93

目前支持+和*两个操作 #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct bign{ int l; int w[100010]; bign(){ l=1; memset(w,0,sizeof(w)); } bign(int x){ l=0; memset(w,0,sizeof(w)); while(x){ w[l]=x; x/=10; ++l; } } bool operator >(bign x){ int i; if(l>x.l) return 1; if(l<x.l) return 0; for(i=l-1;i>=0;i--){ if(w[i]<x.w[i]) return 0; if(w[i]>x.w[i]) return 1; } return 0; } bign operator +(const bign& x){ bign ans; int i; ans.l=max(l,x.l); for(i=0;i<ans.l;i++){ ans.w[i]+=w[i]+x.w[i]; ans.w[i+1]+=ans.w[i]/10; ans.w[i]%=10; } if(ans.w[ans.l]) ans.l++; return ans; } bign operator -(const bign& x){ int i,g=0; bign ans; ans.l=0; for(i=0;i<l;i++){ int tmp=w[i]-g; if(i<x.l) tmp-=x.w[i]; if(tmp<0){ g=1; tmp+=10; } else{ g=0; } ans.w[ans.l++]=tmp; } while(ans.l>0&&!ans.w[ans.l-1]) ans.l--; return ans; } bign operator *(bign &x){ int i,j,tmp; bign ans; ans.l=l+x.l; for(i=0;i<l;i++){ for(j=0;j<x.l;j++){ tmp=ans.w[i+j]+w[i]*x.w[j]; ans.w[i+j+1]+=tmp/10; ans.w[i+j]=tmp; } } while(ans.l>0&&!ans.w[ans.l-1]) ans.l--; return ans; } void read(){ char c=getchar(); int x=0,ww=1,i; int tmp[100010]; l=0; while(!isdigit(c)&&c!='-') c=getchar(); if(c=='-'){ c=getchar(); ww=-1; } while(isdigit(c)){ tmp[l++]=(int)(c-'0'); c=getchar(); } for(i=0;i<l;i++) w[i]=tmp[l-i-1]; } void write(){ int i; if(l==0) puts("0"); for(i=l-1;i>=0;i--){ printf("%d",w[i]); } printf("\n"); } }; int main() { bign a,b,c; a.read(); b.read(); c=a*b; c.write(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-78766.html

最新回复(0)