Java之大数加减乘除——除法

发布时间 2023-04-17 00:16:20作者: 杪冬的鸡汤不好喝

上节说到乘法是利用循环+加法,其实减法也是一样的,9/3就是9-3-3-3,减了三次这样的。

但是减法就是要考虑除数和被除数之间的关系。

void divide(BigLong b){
int ia=this.num.length;
int ib=b.num.length;
int m=ia,n=ib;
int[] big=this.num;
int[] small=b.num;
if(ib>ia){
System.out.print("0");
return;
}

int i,j,z,tmp,rezult=1,f=0;


while(m>n){
rezult++;
int flag=0;
int[] count=new int[m+2];
for (i=m-1,j=n-1,z=m+1;i*j>0;i--,j--,z--){
tmp=count[z]+big[i]-small[j];
if(tmp<0){
count[z-1]=-1;
count[z]=count[z]+10+big[i]-small[j];
}else{
count[z]=tmp;
}
}
tmp=count[z]+big[i]-small[j];
if(tmp<0){
count[z-1]=-1;
count[z]=count[z]+10+big[i]-small[j];
}else{
count[z]=tmp;
}
i--;
j--;
z--;

if(i>-1){
while(i>=0){
count[z]=count[z]+big[i];
i--;
z--;
}
}
if(j>-1){
while(j>=0){
count[z]=count[z]+small[j];
j--;
z--;
}
}

for(i=m+1;i>=0;i--){
if(count[i]>=10){
count[i]=count[i]%10;
count[i-1]=count[i-1]+1;
}
}
String str="";
for(i=0;i<count.length;i++){
if(count[i]==0 && flag==0){
continue;
}
if(count[i]!=0) flag=1;
if(flag==1){
str=str+""+count[i];
}

}




BigLong p=new BigLong(str);
big=p.num;
m=big.length;

}
System.out.print(rezult);
}

偷了一个小懒,就是如果被除数小于除数就直接罢工,不干了(返回0),差不多都是四舍五入的,没有很精确,精确的话其实也不难的,就是在后面补0还是用的减法思维。

 

 

 

 

 

 

 

 

 

void divide(BigLong b){
int ia=this.num.length;
int ib=b.num.length;
int m=ia,n=ib;
int[] big=this.num;
int[] small=b.num;
if(ib>ia){
System.out.print("0");
return;
}

int i,j,z,tmp,rezult=1,f=0;


while(m>n){
rezult++;
int flag=0;
int[] count=new int[m+2];
for (i=m-1,j=n-1,z=m+1;i*j>0;i--,j--,z--){
tmp=count[z]+big[i]-small[j];
if(tmp<0){
count[z-1]=-1;
count[z]=count[z]+10+big[i]-small[j];
}else{
count[z]=tmp;
}
}
tmp=count[z]+big[i]-small[j];
if(tmp<0){
count[z-1]=-1;
count[z]=count[z]+10+big[i]-small[j];
}else{
count[z]=tmp;
}
i--;
j--;
z--;

if(i>-1){
while(i>=0){
count[z]=count[z]+big[i];
i--;
z--;
}
}
if(j>-1){
while(j>=0){
count[z]=count[z]+small[j];
j--;
z--;
}
}

for(i=m+1;i>=0;i--){
if(count[i]>=10){
count[i]=count[i]%10;
count[i-1]=count[i-1]+1;
}
}
String str="";
for(i=0;i<count.length;i++){
if(count[i]==0 && flag==0){
continue;
}
if(count[i]!=0) flag=1;
if(flag==1){
str=str+""+count[i];
}

}




BigLong p=new BigLong(str);
big=p.num;
m=big.length;

}
System.out.print(rezult);
}