巨大数的乘法

通过之前巨大数的获取可知,当前巨大数是按4位4位分开存放的。

对于乘法举个例子:12345 × 3456
内部逻辑是:
1 2345 × 3456 = (1 × 10000 ^ 1 ) × (3456 × 10000 ^ 0) + (2345 × 10000 ^ 0)× (3456 × 10000 ^ 0)
可以发现乘法实际是多项式乘法,万的次方对应的是元素下标,若万的次方相同,可以视作同类项进行合并(实际就是在该下标位置进行相加)。

任何计算前,需要考虑高低位的问题,计算都是由低位向高位计算,所以每次计算前进行一次翻转操作:

boolean reverse(HUGE *huge) {
     
	HUGE tmp;
	int count;
	int i;
	count = (huge->size + 3) / 4;

	tmp.data = (int *) calloc(sizeof(int), count);

	for (i = 0; i < count; i++) {
     
		tmp.data[i] = huge->data[count - i - 1];
	}
	for (i = 0; i < count; i++) {
     
		huge->data[i] = tmp.data[i];
	}

	free(tmp.data);
}

这样乘法就能完成了:

boolean multiply(HUGE huge1, HUGE huge2, HUGE *result) {
     
	int size;
	int count1;
	int count2;
	int count3;
	int i;
	int j;
	int tmp = 0;
	int data;
	size = huge1.size + huge2.size;
	count1 = (huge1.size + 3) / 4;
	count2 = (huge2.size + 3) / 4;
	count3 = (size + 3) / 4;

	result->data = (int *) calloc(sizeof(int), count3);
	result->size = size;
	result->sign = huge1.sign ^ huge2.sign;

	reverse(&huge1);
	reverse(&huge2);
	for (i = 0; i < count1; i++) {
     
		for (j = 0; j < count2; j++) {
     
			data = huge1.data[i] * huge2.data[j] + result->data[i + j];
			tmp = data / 10000;
			data %= 10000;
			result->data[i + j] = data;
			result->data[i + j + 1] = tmp;
		}
	}

	reverse(result);
	reverse(&huge1);
	reverse(&huge2);
}

因为万的次数对应下标,则结果应该加到下标为i + j的元素上(一万的i次方×一万的j次方结果为一万的i+j次方)

你可能感兴趣的:(巨大数的乘法)