首页 > 代码库 > 大数相乘

大数相乘


#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void multiply(char* a, char* b, char* c)
{
	int sa = 0;
	int sb = 0;
	int i,j;
	int *result = NULL;

	if ((NULL == a) || (NULL == b) || (NULL == c))
	{
		return ;
	}

	sa = strlen(a);
	sb = strlen(b);
	result = (int*)malloc(sizeof(int) * (sa+sb));

	//把存放结果的数组清零
	//memset(result, 0, sizeof(result));
	for (i = 0; i < sa+sb; i++)
	{
		result[i] = 0;
	}

	for (i = 0; i < sa; i++)
	{
		for (j = 0; j< sb; j++)
		{
			result[i+j] += (*(a+sa-i-1) - '0') * (*(b+sb-j-1) - '0');
		}
	}

	//进位
	for (i = 0; i < sa+sb; i++)
	{
		result[i+1] += result[i] / 10;
		result[i] %= 10;
	}

	//出参赋值
	i = sa+sb-1;
	if (result[i] == 0)
	{
		i--;
	}

	for (; i >=0; i--)
	{
		*c++ = result[i] + '0';
	}
	*c = '\0';

	free(result);
	return ;
}


void main()
{
	char *a = "52364";
	char *b = "68746";
	char c[100] = {0};

	multiply(a, b, c);

	return ;
}


大数相乘