您的位置:首页 > 其它

大数相乘

2011-09-15 17:17 190 查看
#include <stdio.h>
#include <assert.h>

void BigNumMultiply(const char *str1, const char *str2, char *product)
{
assert(str1 != NULL && str2 != NULL && product != NULL);

int i, j;
int len1 = (int)strlen(str1);
int len2 = (int)strlen(str2);
int *dest = (int*)malloc(sizeof(int)*(len1+len2+1));

for (i=0; i<len1+len2+1; i++) { dest[i] = 0; }

for (i=0; i<len1; i++)
{
for (j=0; j<len2; j++)
{
dest[i+j+1] += (str1[i]-'0')*(str2[j]-'0');
}
}

for (i=len1+len2-1; i>=0; i--)
{
// 当i=0时dest[0]=0,这个条件不成立,所以不用担心dest[-1]
if (dest[i] >= 10)
{
dest[i-1] += dest[i]/10;
dest[i] %= 10;
}
product[i] = dest[i]+'0';
}

if (product[0] == '0')
{
i = 1;
while (product[i] != '\0')
{
product[i-1] = product[i];
i++;
}
product[i-1] = '\0';
}

free(dest);
return;
}

int main(void)
{
char product[50] = {0};

BigNumMultiply("234324", "54651", product);
printf("%s\n", product);

getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: