一、高精度加法
#include<iostream>
#include<string>
using namespace std;
const int N = 1e6+10;
int a[N],b[N],c[N];
int la,lb,lc;
void add(int c[],int a[],int b[])
{
for(int i = 0;i < lc;i++)
{
c[i] += a[i] + b[i];
c[i+1] = c[i] / 10;
c[i] %= 10;
}
if(c[lc]) lc++;
}
int main()
{
string x,y;cin >> x >> y;
la = x.size();lb = y.size();lc = max(la,lb);
for(int i = 0;i < la;i++) a[la-i-1] = x[i]-'0';
for(int i = 0;i < lb;i++) b[lb-i-1] = y[i]-'0';
add(c,a,b);
for(int i = lc-1;i >= 0;i--) cout << c[i];
return 0;
}
二、高精度减法
#include<iostream>
#include<string>
using namespace std;
const int N = 1e6+10;
int a[N],b[N],c[N];
int la,lb,lc;
//比大小
bool comp(string& x,string& y)//y>x返回true
{
if(x.size() != y.size()) return y.size() > x.size();
//位数相等
return y > x;
}
//高精度减法
void sub(int c[],int a[],int b[])//a>b
{
for(int i = 0;i < lc;i++)
{
c[i] += a[i]-b[i];
if(c[i] < 0)
{
c[i+1]--;
c[i] += 10;
}
}
while(lc > 1 && c[lc-1] == 0) lc--;
}
int main()
{
string x,y;cin >> x >> y;
if(comp(x,y))
{
swap(x,y);
cout << "-";
}
la = x.size();lb = y.size();lc = max(la,lb);
for(int i = 0;i < la;i++) a[la-i-1] = x[i]-'0';
for(int i = 0;i < lb;i++) b[lb-i-1] = y[i]-'0';
sub(c,a,b);
for(int i = lc-1;i >= 0;i--) cout << c[i];
return 0;
}
三、高精度乘法
#include<iostream>
#include<string>
using namespace std;
const int N = 1e6+10;
int a[N],b[N],c[N];
int la,lb,lc;
void mul(int c[],int a[],int b[])
{
for(int i = 0;i < la;i++)
{
for(int j = 0;j < lb;j++)
{
c[i+j] += a[i]*b[j];
}
}
for(int i = 0;i < lc;i++)
{
c[i+1] += c[i]/10;
c[i] %= 10;
}
while(lc > 1 && c[lc-1] == 0) lc--;
}
int main()
{
string x,y;cin >> x >> y;
la = x.size();lb = y.size();lc = la+lb;
for(int i = 0;i < la;i++) a[la-i-1] = x[i]-'0';
for(int i = 0;i < lb;i++) b[lb-i-1] = y[i]-'0';
mul(c,a,b);
for(int i = lc-1;i >= 0;i--) cout << c[i];
return 0;
}
四、高精度除法(高精度除以低精度)
由于高精度除以高精度的场景较为少见,算法竞赛中基本不会使用,所以这里并没有做整理。
#include<iostream>
#include<string>
using namespace std;
const int N = 1e6+10;
int a[N],b,c[N];
int la,lc;
void div(int c[],int a[],int b)//高精度除以低精度
{
long long tmp = 0;//余数
for(int i = la-1;i >= 0;i--)
{
tmp = tmp*10 + a[i];
c[i] = tmp / b;
tmp %= b;
}
while(lc > 1 && c[lc-1] == 0) lc--;
}
int main()
{
string x;cin >> x >> b;
la = x.size(); lc = la;
for(int i = 0;i < la;i++) a[la-i-1] = x[i]-'0';
div(c,a,b);
for(int i = lc-1;i >= 0;i--) cout << c[i];
return 0;
}