高精度加法:
#include<bits/stdc++.h>
using namespace std;
const int maxnn = 505;
char a1[maxnn], b1[maxnn];
int a[maxnn], b[maxnn], c[maxnn];
int main(){
cin >> a1 >> b1;
int t1 = strlen(a1), t2 = strlen(b1);
for(int i = 1; i <= t1; i++) a[i] = a1[t1 - i] - '0';
for(int i = 1; i <= t2; i++) b[i] = b1[t2 - i] - '0';
int maxn = max(t1, t2);
for(int i = 1; i <= maxn; i++){
c[i] += a[i] + b[i];
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
if(maxn + 1 != 0) maxn++;
while(c[maxn] == 0 && maxn > 1) maxn--;
for(int i = maxn; i >= 1; i--) cout << c[i];
return 0;
}
高精度减法:
#include<bits/stdc++.h>
using namespace std;
const int ttt = 100860;
char a1[ttt], b1[ttt];
int a[ttt], b[ttt], c[ttt];
bool flag = 1;
int main(){
cin >> a1 >> b1;
int t1 = strlen(a1), t2 = strlen(b1);
for(int i = 1; i <= t1; i++) a[i] = a1[t1 - i] - '0';
for(int i = 1; i <= t2; i++) b[i] = b1[t2 - i] - '0';
int maxn = max(t1, t2);
for(int i = 0; i < maxn; i++){
if(t1 > t2) break;
if(a1[i] < b1[i] || t1 < t2){
flag = 0;
break;
}
if(a1[i] > b1[i]) break;
}
if(flag == 1){
for(int i = 1; i <= maxn; i++){
c[i] += a[i] - b[i];
if(c[i] < 0){
c[i] += 10;
c[i + 1]--;
}
}
}
else{
for(int i = 1; i <= maxn; i++){
c[i] += b[i] - a[i];
if(c[i] < 0){
c[i] += 10;
c[i + 1]--;
}
}
}
if(c[maxn + 1] != 0) maxn++;
while(c[maxn] == 0 && maxn > 1) maxn--;
for(int i = maxn; i >= 1; i--){
if(flag == 0 && i == maxn) cout << "-";
cout << c[i];
}
return 0;
}
高精度乘法:
#include<bits/stdc++.h>
using namespace std;
const int ttt = 20050;
char a1[ttt], b1[ttt];
int a[ttt], b[ttt], c[ttt];
int main(){
cin >> a1 >> b1;
int t1 = strlen(a1), t2 = strlen(b1);
for(int i = 1; i <= t1; i++) a[i] = a1[t1 - i] - '0';
for(int i = 1; i <= t2; i++) b[i] = b1[t2 - i] - '0';
int maxn = t1 + t2;
for(int i = 1; i <= t2; i++) for(int j = 1; j <= t1; j++) c[i + j - 1] += a[j] * b[i];
for(int i = 1; i < maxn; i++){
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
if(c[maxn + 1] != 0) maxn++;
while(c[maxn] == 0 && maxn > 1) maxn--;
for(int i = maxn; i >= 1; i--) cout << c[i];
return 0;
}