实现大位数相乘算法

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

实现一个计算大位数(如100位以上)相乘结果的函数(请完全用算法实现)

#include<iostream.h>

#include<string.h>

#include<stdio.h>

multiply(char * a_strMultp1,char * a_strMultp2)

{

int Len1; // the length of multiplier1

int Len2; // the length of multiplier2

Len1 = strlen(a_strMultp1);

Len2 = strlen(a_strMultp2);

char *strRet= new char(iMultp1Len+iMultp2Len); // the result;

memset(strRet,'0',iMultp1Len+iMultp2Len);

// if either's length is 0,then exit;

if(Len1 <= 0 || Len 2<= 0)

{

cout<<"error"<<endl;

exit(0);

}

int i;

int j;

int iCarry; // the Carry;

int iDigit; // the Digit;

iCarry = 0;

iDigit = 0;

int len;

int temp = 0;

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

{

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

{ int jj =Len2+Len1-j-i-2;

iDigit = (a_strMultp2[i] - '0')*(a_strMultp1[j] - '0') + iCarry;

iCarry = iDigit / 10;

iDigit = iDigit % 10;

temp = strRet[jj] - '0' +iDigit;

if (temp/10)

iCarry = iCarry + temp/10;

strRet[jj]= temp%10 + '0';

if (iCarry)

strRet[jj+1]=iCarry%10 + strRet[jj+1];

iCarry = iCarry /10;

}

}

if (iCarry)

{

strRet[Len2+Len1-1]= iCarry + '0';

len = Len2+Len1-1;

}

else

len = Len2+Len1-2;

for (i = len;i>=0;i--)

cout<<strRet[i];

cout<<endl;

}

main()

{

multiply("177856","196196");

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有