简单模拟就可以实现高精度加、减、乘、除(高精度除以低精度)
/*
* template:高精度算法
* date:2020/08/22
*/
#include<iostream>
#include<string>
using namespace std;
const int MAXLEN=1001;
typedef struct {
int len;
int num[MAXLEN];
} HugeInt;
bool negative;
//大数输入
HugeInt scanHugeInt() {
string s;
HugeInt hugeInt;
cin>>s;
hugeInt.len=s.size();
for(int i=0; i<s.size(); i++) {
hugeInt.num[hugeInt.len-i]=s[i]-'0';
}
return hugeInt;
}
//大数加法
HugeInt plusHugeInt(HugeInt a,HugeInt b) {
int i;
HugeInt res;
res.len=a.len>b.len?a.len:b.len;
for(i=1;i<=res.len;i++) res.num[i]=0;
for(i=1; i<=res.len; i++) {
res.num[i]+=a.num[i]+b.num[i];
res.num[i+1]=res.num[i]/10;
res.num[i]=res.num[i]%10;
}
return res;
}
//大数减法
HugeInt minusHugeInt(HugeInt a,HugeInt b) {
int i;
HugeInt res;
negative=false;
if(a.len<b.len) {
negative=true;
} else if(a.len==b.len) {
for(i=1; i<=a.len; i++) {
if(a.num[i]<b.num[i]) {
negative=true;
break;
}
}
}
if(negative) {
HugeInt t=a;
a=b;
b=t;
}
res.len=a.len;
for(i=1; i<=res.len; i++) {
if(a.num[i]<b.num[i]) {
a.num[i+1]--;
a.num[i]+=10;
}
res.num[i]=a.num[i]-b.num[i];
}
while(res.num[res.len]==0&&res.len!=1) res.len--;
return res;
}
//高精度乘法
HugeInt mutiplyHugeInt(HugeInt a,HugeInt b) {
int i;
int x;//进位
HugeInt res;
res.len=a.len+b.len;
for(i=1; i<=res.len; i++) res.num[i];
for(i=1; i<=a.len; i++) {
x=0;
for(int j=1; j<=b.len; j++) {
res.num[i+j-1]+=a.num[i]*b.num[j]+x;
x=res.num[i+j-1]/10;
res.num[i+j-1]%=10;
}
res.num[i+b.len]=x;
}
while(res.num[res.len]==0&&res.len!=1) res.len--;
return res;
}
//高精度除法(高精度除以低精度)
HugeInt divideSmallInt(HugeInt a,int b) {
HugeInt res;
int x;//余数
res.len=a.len;
x=0;
for(int i=a.len; i>=1; i--) {
res.num[i]=(a.num[i]+x*10)/b;
x=(a.num[i]+x*10)%b;
}
while(res.num[res.len]==0&&res.len!=1) res.len--;
return res;
}
int main() {
HugeInt a=scanHugeInt();
HugeInt b=scanHugeInt();;
int c;
cin>>c;
HugeInt plus=plusHugeInt(a,b);
HugeInt minus=minusHugeInt(a,b);
HugeInt mutiply=mutiplyHugeInt(a,b);
HugeInt divide=divideSmallInt(a,c);
cout<<"plus:";
int i;
for(i=plus.len; i>=1; i--) cout<<plus.num[i];
cout<<endl;
cout<<"minus:";
if(negative) cout<<"-";
for(i=minus.len; i>=1; i--) cout<<minus.num[i];
cout<<endl;
cout<<"mutiply:";
for(i=mutiply.len; i>=1; i--) cout<<mutiply.num[i];
cout<<endl;
cout<<"divide:";
for(i=divide.len; i>=1; i--) cout<<divide.num[i];
cout<<endl;
return 0;
}