var i=0,len=0; var BigNum=function (s,sign){//+1为正,-1为负 this.bn=typeof s=="string"?BigNum.big(s.replace('-','')):s; this.deal();//处理减法导致的前0 this.s=(Object.prototype.toString.apply(s) === '[object Array]'?this.show():s).replace('-','');//不含符号 this.sign=typeof s=="string"?(s.charAt(0)=='-'?-1:1):(sign==-1?-1:1); }; BigNum.weight=100000000;//好像js的运算精确度知道16位 BigNum.wLen=8;//BigNum.weight.toString().length; for(i=0,len=BigNum.wLen;i< len;i++) { BigNum["zero"+i]=(1<< i).toString(2).substr(1);//可以定义静态的,i可以到30,即32位,首位为符号位,30个0 } BigNum.big=function(s){ var len=BigNum.wLen,l=Math.ceil(s.length/len)-1,r=[],i=0; for(i=0;i< l;i++){ r[i]=parseInt(s.substr(-1*(i+1)*len,len),10); } r[i]=parseInt(s.substr(0,s.length%len||len),10); return r; } BigNum.prototype.show=function() { var bn=this.bn,l=bn.length-1,i=1,r=[]; r[0]=""+bn[l]; while(l--){ r[++i]=BigNum["zero"+(BigNum.wLen-bn[l].toString().length)]+bn[l]; } return this.sign==1?r.join(""):'-'+r.join(""); }; BigNum.prototype.deal=function() { var i=this.bn.length; while(i--){ if(this.bn[i]!=0||i==0) break; } this.bn.length=i+1; }; BigNum.prototype.add=function(b){ var r=[],a=this,an=a.bn,bn=b.bn,la=an.length,lb=bn.length,i=0,len=la>lb?la:lb,m=0,t=0; if(a.sign==b.sign){ for(;i< len;i++){ t=(an[i]||0)+(bn[i]||0)+m; r[i]=t%BigNum.weight; m=Math.floor(t/BigNum.weight); } if(m>0){ r[i]=m; } return new BigNum(r,a.sign); }else{ var m=this.compare(b); if(m==0){ return new BigNum('0'); }else{ if(m<0){ la=lb,an=bn,bn=a.bn; } for(i=0;i< la;i++){ t=an[i]-(bn[i]||0)+t; if(t>=0){ r[i]=t; t=0; } else {r[i]=t+BigNum.weight;t=-1;} } return new BigNum(r,m>0?a.sign:b.sign); } } } BigNum.prototype.multi=function(b){ var a=this,an=a.bn,la=an.length,bn=b.bn,lb=bn.length,c=[],t=[],r=[],m=0,n=0,i=0,j=0,l=la+lb-1; if(lb>la){ an=bn,la=lb,bn=this.bn,lb=bn.length; } for(i=0;i< lb;i++){ c=t[t.length]=[]; for(j=0;j< la;j++){ c[j]=an[j]*bn[i]; } } for(n=0;n< l||m>0;n++){ r[n]=m; for(i=0;i< lb&&i<=n;i++){ j=n-i; if(j< la){ r[n]+=t[i][j]; } } m=Math.floor(r[n]/BigNum.weight); r[n]%=BigNum.weight; } return new BigNum(r,this.sign*b.sign); } BigNum.prototype.compare=function(b){//绝对值的大小比较 return>0 a>b var len=this.s.length,a=len-b.s.length,i=0,t=0; if(a!=0){ return a; } for(;i< len;i++){ t=this.s.charCodeAt(i)-b.s.charCodeAt(i); if(t!=0){ return t; } } return 0; }