大整数乘法的C++程序

以下是自己写的两个大整数乘法的程序:

//the progrom is used to calculate the product of two large integer
//It is need a input file named abc.txt which is formated as follows:
//  m  //the integer m means that the first large integer have m median
//  p  //the integer p is the first large integer
//  n  //the integer n means that the second large integer have n median
//  q  //the integer q is the second large integer
//for instance,we have a input file as follows:
//  3
//  1 2 7
//  3
//  175

#include<iostream>
#include<fstream>
#include<vector>

using namespace std;

void input(vector<int> &a,vector<int> &b,int &m,int &n);
void MulOfBigInt(const vector<int> a,const vector<int> b,vector<int> &c);
void print(const vector<int> c);

int main()
{
  int i,j,m=0,n=0;
 
  vector<int> a(m);
  vector<int> b(n);
 
  input(a,b,m,n);//从文件读入数据

  vector<int> c(m+n);
  vector<int> a1(m);
  vector<int> b1(n);

  for(i=0;i<m;i++)//将输入数据转换为适合处理的数据,即对数组a,b中的数据转置
   a1[m-i-1]=a[i];
  for(j=0;j<n;j++)
   b1[n-j-1]=b[j];
 
  MulOfBigInt(a1,b1,c);//调用大整数乘法函数
  print(c);   //输出结果
  return 0;
}

//input function
void input(vector<int> &a,vector<int> &b,int &m,int &n)
{
  ifstream in("abc.txt");
  int i,j;

  in>>m;
  a.resize(m);
  for(i=0;i<m;i++)
   in>>a[i];

  in>>n;
  b.resize(n);
  for(j=0;j<n;j++)
   in>>b[j];
}

//the function of product of two large integer
void MulOfBigInt(const vector<int> a,const vector<int> b,vector<int> &c)
{
 int temp1,temp2;
 int m=a.size(),n=b.size();
 for(int i=0;i<n;i++)
  for(int j=0;j<m;j++)               
  {
   temp1=b[i]*a[j];
   if(temp1>=10)
   {
    c[i+j]+=temp1%10;
    c[i+j+1]+=temp1/10;
       if(c[i+j]>=10||c[i+j+1]>=10)
        goto L;
   }
   else
   {
    c[i+j]+=temp1;
    if(c[i+j]>=10)
    {
                    L:temp2=c[i+j];
     c[i+j]=temp2%10;
     c[i+j+1]+=temp2/10;
    }
   }
  }
}

//output function
void print(const vector<int> c)

 int n=c.size();
 for(int i=1;;)
 {
    if(c[n-i]==0)
       i++;
    else
    {
     for(int j=n-i;j>=0;j--)
        cout<<c[j];
     cout<<endl;
     return;
    }
 }

以下是一个测试数据:

abc.txt

60
1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7
62
4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 4 3 7 1 4 3 5 3 8 6 1 3

结果:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值