以下是自己写的两个大整数乘法的程序:
//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
结果: