实现大位数相乘算法

类别:软件工程 点击:0 评论:0 推荐:
实现一个计算大位数(如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");
 }

本文地址:http://com.8s8s.com/it/it33447.htm