高精度除法算法详解及代码实现
这是一个实现高精度除法的程序,主要思路是模拟手算除法的过程。具体步骤如下:
-
将被除数和除数转换成整型数组,并将数组清零。
-
通过比较被除数和除数的长度,确定两者之间的差值。
-
将除数向左移动差值个位置,使其与被除数的位数相同。
-
从被除数的最高位开始,依次尝试将除数乘以1、2、3……,直到乘积大于被除数,记录下最后一次乘法的结果。
-
将被除数减去上一步得到的乘积,得到余数,将余数作为新的被除数,继续执行步骤4,直到被除数小于除数为止。
-
将每一次得到的商记录下来,最后输出结果。
在实现过程中,还需要注意处理进位和借位的情况。具体细节可以参考代码注释。
setZero(a,1000);
setZero(b,1000);
setZero(c,1000);
printf('%s / %s = ',str1,str2);
int i,j,tmp,tmp2=0,borrow=0,temp[1000]={0},temp2[1000]={0};
while(compare(a,b)>=0){
tmp=len1-len2;
if(tmp==tmp2&&tmp>0)
tmp--;
tmp2=tmp;
setZero(temp2,1000);
for(i=len1-1;i>=tmp;i--)
temp2[i]=b[i-tmp];
copy(temp,a);
if(compare(temp,temp2)<0)
continue;
for(j=1;;j++){
borrow=0;
for(i=tmp;i<len1;i++){
temp[i]=a[i]-temp2[i]-borrow;
if(temp[i]<0){
borrow=1;
temp[i]+=10;
}
else
borrow=0;
}
len1=copy(a,temp);
c[tmp]=j;
if(compare(temp,temp2)<0)
break;
}
}
for(i=999;c[i]==0;i--);
for(;i>=0;i--)
printf('%d',c[i]);
printf('
');
}
原文地址: https://www.cveoy.top/t/topic/oJNh 著作权归作者所有。请勿转载和采集!