写这篇博客的原因是每次做题的时候,如果遇到了需要高精度运算的题目,每次都要写一遍;而且对于一些复杂的问题,把高精度运算函数单独写出来,程序更加地简洁明了。
使用前请注意:
1.输入:以下的函数输入的大整数类型都是string,而且是正序输入的;
2.输出:以下的函数输出的结果类型都是string,而且是正序输出的;
3.整形数组的长度:按照题目要求来定义整形数组的长度。
1.高精度加法:
string gjjia(string a1,string b1)
{
int lena=a1.length(),lenb=b1.length(),a[200]={},b[200]={},c[200]={},lenc,i,x;
string result;
for(i=0;i<=lena-1;i++) a[lena-i]=a1[i]-'0';
for(i=0;i<=lenb-1;i++) b[lenb-i]=b1[i]-'0';
lenc=1;x=0;
while(lenc<=lena||lenc<=lenb)
{
c[lenc]=a[lenc]+b[lenc]+x;
x=c[lenc]/10;
c[lenc]%=10;
lenc++;
}
c[lenc]=x;
if(c[lenc]==0)
lenc--;
for(i=lenc;i>=1;i--)
result+=c[i]+'0';
return result;
}
2.高精度减法(结果取绝对值):
string gjjian(string a1,string b1)
{
int lena=a1.length(),lenb=b1.length(),a[250]={},b[250]={},c[250]={},lenc,i;
if(lena1)lenc--;
for(i=lenc;i>=1;i--)
result+=c[i]+'0';
return result;
}
3.高精度乘法:
string gjcheng(string a1,string b1)
{
int a[200]={},b[200]={},c[500]={},lena=a1.length(),lenb=b1.length(),lenc,i,j,x;
string result;
for(i=0;i<=lena-1;i++) a[lena-i]=a1[i]-'0';
for(i=0;i<=lenb-1;i++) b[lenb-i]=b1[i]-'0';
for(i=1;i<=lena;i++)
{
x=0;
for(j=1;j<=lenb;j++)
{
c[i+j-1]=a[i]*b[j]+x+c[i+j-1];
x=c[i+j-1]/10;
c[i+j-1]%=10;
}
c[i+lenb]=x;
}
lenc=lena+lenb;
while(c[lenc]==0&&lenc>1)
lenc--;
for(i=lenc;i>=1;i--)
result+=c[i]+'0';
return result;
}
4.高精度除以低精度:
string gjchudj(string a1,int b)
{
int a[200]={},c[200]={},lena=a1.length(),i,x=0,lenc;
string result;
for(i=0;i<=lena-1;i++)
a[i+1]=a1[i]-'0';
for (i=1;i<=lena;i++)
{
c[i]=(x*10+a[i])/b;
x=(x*10+a[i])%b;
}
lenc=1;
while(c[lenc]==0&&lenc
5.运算符重载:
#include
#include
using namespace std;
const int Base=1000000000;
const int Capacity=100;
typedef long long huge;
struct BigInt
{
int Len;
int Data[Capacity];
BigInt() : Len(0) {}
BigInt (const BigInt &V) : Len(V.Len)
{
memcpy (Data, V.Data, Len*sizeof*Data);
}
BigInt(int V) : Len(0)
{
for(; V>0; V/=Base) Data[Len++]=V%Base;
}
BigInt &operator=(const BigInt &V)
{
Len=V.Len;
memcpy(Data, V.Data, Len*sizeof*Data);
return *this;
}
int &operator[] (int Index)
{
return Data[Index];
}
int operator[] (int Index) const
{
return Data[Index];
}
};
int compare(const BigInt &A, const BigInt &B)
{
if(A.Len!=B.Len) return A.Len>B.Len ? 1:-1;
int i;
for(i=A.Len-1; i>=0 && A[i]==B[i]; i--);
if(i<0)return 0;
return A[i]>B[i] ? 1:-1;
}
BigInt operator + (const BigInt &A,const BigInt &B)
{
int i,Carry(0);
BigInt R;
for(i=0; i0; i++)
{
if(i0&&R[R.Len-1]==0) R.Len--;
return R;
}
BigInt operator * (const BigInt &A,const BigInt &B)
{
int i;
huge Carry(0);
BigInt R;
for(i=0; i0; i++)
{
if(i>(istream &In,BigInt &V)
{
char Ch;
for(V=0; In>>Ch;)
{
V=V*10+(Ch-'0');
if(In.peek()<=' ') break;
}
return In;
}
ostream &operator<<(ostream &Out,const BigInt &V)
{
int i;
Out<<(V.Len==0 ? 0:V[V.Len-1]);
for(i=V.Len-2; i>=0; i--) for(int j=Base/10; j>0; j/=10) Out<>a>>b;
cout<<"+"<0) cout<<"-"<