实现大位数相乘算法
2004-12-10 21:31
141 查看
实现一个计算大位数(如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");
}
#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");
}
相关文章推荐
- 算法:C++实现大数相乘
- 左移/右移指定位数字符串 (算法http://blog.csdn.net/v_JULY_v/article/details/6322882 的实现)
- 大数相乘问题--算法思想及Java实现解析(附详细注释)
- PHP实现RSA加解密算法示例(生成密钥位数为1024位的方法)
- 大数相乘的算法实现
- 矩阵相乘优化算法实现讲解
- 大数相乘的算法实现(C#)
- C++实现的大数相乘算法示例
- 加农算法的MPI实现 【矩阵相乘】
- 矩阵相乘算法的Java语言实现
- 求逆矩阵以及两矩阵相乘的算法实现
- 两个数相乘,小数点后位数没有限制,请写一个高精度算法【转】
- 算法:【一列数的规则如下: 1、1、2、3、5、8、13、21、34 ,求第30位数是多少, 用递归算法实现。(C#语言)】
- 算法系列:矩阵相乘算法的MapReduce实现
- 大数相乘算法实现
- MapReduce框架中矩阵相乘的算法思路及其实现
- 每天一个算法之打印1到n位数(用数组实现)
- 大数相加与相乘算法实现
- 一些算法的MapReduce实现——矩阵相乘一步实现
- 25与一个三位数相乘个位是0,与这个三位数相加有且只有1次进位,像这样的三位数总共有多少个?C#实现