/*
基本的思想是反复做减法,看看从被除数里最多能减去多少个除数,商就是多少。一个减法显然太慢了,如何能减得更快呢?
以7546除以23为例来看一下:开始商为0。先减去23的100倍,就是2300,发现减3次,余下646。于是商的值就增加300.然后用
646减去230,发现减够2次,余下186,于是商的值增加20。最后用186减去23,够减8次,因此最终商就是328。
核心是要写一个大整数的减法函数,然后反复调用该函数进行减法操作。
计算除数的10倍,100倍的时候,不用做乘法,直接在除数后面补0即可。
*/
#include <stdio.h>
#include <string.h>
#define MAX_LEN 200
char szLine1[MAX_LEN + 10];
char szLine2[MAX_LEN + 10];
int an1[MAX_LEN + 10]; //被除数,an1[0]对应于个位
int an2[MAX_LEN + 10]; //除数,an2[0]对应于个位
int aResult[MAX_LEN + 10]; //存放商,aResult[0]对应于个位
/*
Substract函数:长度nLen1的大整数p1减去长度nLen2的大整数p2减得结果放在p1里,返回值代表结果的长度,如果不够减
返回-1,正好减完返回0。p1[0],p2[0]代表个位。
*/
int Substract(int *p1, int *p2, int nLen1, int nLen2) {
int i;
if(nLen1 < nLen2) return -1;
//判断p1是否比p2大,如果不是,返回-1
bool bLarger = false;
if(nLen1 == nLen2) {
for(i = nLen1 - 1; i >= 0; i --) {
if(p1[i] > p2[i]) bLarger = true;
else if(p1[i] < p2[i]) {
if(!bLarger) return -1;
}
}
}
for(i = 0; i < nLen2; i ++) {
p1[i] -= p2[i];
if(p1[i] < 0) {
p1[i] += 10;
p1[i + 1] --;
}
}
for(i = nLen1 - 1; i >= 0; i --) {
if(p1[i]) return i + 1;
}
return 0;
}
int main()
{
int t, n;
char szBlank[20];
scanf("%d", &n);
for(t = 0; t < n; t ++) {
scanf("%s", szLine1);
scanf("%s", szLine2);
int i, j;
int nLen1 = strlen(szLine1);
int nLen2 = strlen(szLine2);
memset(an1, 0, sizeof(an1));
memset(an2, 0, sizeof(an2));
memset(aResult, 0, sizeof(aResult));
j = 0;
for(i = nLen1 - 1; i >= 0; i --)
an1[j ++] = szLine1[i] - '0';
j = 0;
for(i = nLen2 - 1; i >= 0; i --)
an2[j ++] = szLine2[i] - '0';
if(nLen1 < nLen2) {
printf("0\n");
continue;
}
nLen1 = Substract(an1, an2, nLen1, nLen2);
if(nLen1 < 0) {
printf("0\n");
continue;
}
else if(nLen1 == 0) {
printf("1\n");
continue;
}
aResult[0] ++;
int nTimes = nLen1 - nLen2;
if(nTimes < 0) goto OutputResult;
else if(nTimes > 0) {
//将an2乘以10的某次幂,使得结果长度和an1相同
for(i = nLen1 - 1; i >= 0; i --) {
if(i >= nTimes) an2[i] = an2[i - nTimes];
else an2[i] = 0;
}
}
nLen2 = nLen1;
for(j = 0; j <= nTimes; j ++) {
int nTmp;
//一直减到不够减为止,先减去若干个an2*(10的nTimes次方),不够减了,再减去若干个an2*(10的nTimes-1次方)
while(nTmp = Substract(an1, an2 + j, nLen1, nLen2 - j) >= 0) {
nLen1 = nTmp;
aResult[nTimes - j] ++; //每成功一次,则将商的相应项位加1
}
}
OutputResult:
for(i = 0; i < MAX_LEN; i ++) {
if(aResult[i] >= 10) {
aResult[i + 1] += aResult[i] / 10;
aResult[i] %= 10;
}
}
bool bStartOutput = false;
for(i = MAX_LEN; i >= 0; i --) {
if(bStartOutput) {
printf("%d", aResult[i]);
}
else if(aResult[i]) {
bStartOutput = true;
printf("%d", aResult[i]);
}
}
if(!bStartOutput) printf("0\n");
printf("\n");
}
return 0;
}
大整数除法的实现
最新推荐文章于 2024-07-14 12:25:25 发布