大数相乘2

算法描述:

            9     8     7

*                 8     7


            63    56    49

      72    64    56             (第一个for循环中的累乘和累加)


      72    127   112  49

      72    127   116  9    

      72    138   6    9

      85    8     6    9                        (第二个for循环中的循环进位)

//大数相乘

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include <string.h>

#include <malloc.h>



void multiply(int *num1, int length1, int *num2, int length2, int *product)

{

	int i, j;

	for (j = length2 - 1; j >= 0; j--)

	{

		for (i = length1 - 1; i >= 0; i--)

		{

			product[i + j] += num1[i] * num2[j];

		}

	}



	for (i = length1 + length2 - 2; i >=1; i--)

	{

		if (product[i] > 10)

		{

			product[i - 1] += product[i] / 10;

			product[i] = product[i] % 10;

		}

	}

}



int main()

{

	char str1[255], str2[255];

	int length1, length2;

	int *num1, *num2;

	int *product;

	int i;



	gets(str1);

	gets(str2);



	length1 = strlen(str1);

	length2 = strlen(str2);



	num1 = malloc(sizeof(int)*length1);

	num2 = malloc(sizeof(int)*length2);

	product = malloc(sizeof(int)*(length1+length2-1));

	memset(product, 0, sizeof(int)*(length1 + length2 - 1));



	for (i = 0; i < length1; i++)

	{

		num1[i] = str1[i] - '0';

	}

	for (i = 0; i < length2; i++)

	{

		num2[i] = str2[i] - '0';

	}



	multiply(num1, length1, num2, length2, product);



	for (i = 0; i < length1+length2-1; i++)

	{

		printf("%d",product[i]);

	}

	return 0;

}

你可能感兴趣的:(大数相乘2)