高精度加法
const int N = 1e5 + 5;
int a[N],b[N],c[N];
void add(int *a,int *b)
{
memset(c,0,sizeof c);
int i,j;
for(j = N-1; j > 0; --j) if(a[j] || b[j]) break;
for(i = 0; i <= j ; ++ i)
{
c[i] += a[i] + b[i];
if(c[i] >= 10)
{
c[i+1] += c[i]/10;
c[i] %= 10;
}
}
for(i = N-1; i > 0; -- i) if(c[i] != 0) break;
for(; i >= 0; -- i)
{
printf("%d",c[i]);
} printf("\n");
}
高精度减法
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
char s[N];
int a[N],b[N],c[N];
bool check(int *a,int *b)
{
for(int i = N-1; i >= 0; -- i)
{
if(a[i] > b[i]) return true;
if(a[i] < b[i]) return false;
}
return true;
}
void sub(int *a,int *b)
{
memset(c,0,sizeof c);
int i,j;
for(j = N-1; j > 0; --j) if(a[j] || b[j]) break;
for(i = 0; i <= j; ++ i)
{
c[i] += a[i] - b[i];
if(c[i] < 0)
{
c[i+1] -= 1;
c[i] += 10;
}
}
for(i = N-1; i > 0; -- i) if(c[i] != 0) break;
for(; i >= 0; -- i)
{
printf("%d",c[i]);
} printf("\n");
}
int n;
int main()
{
scanf("%s",s); n = strlen(s);
for(int i = 0; i < n; ++ i)
{
a[i] = s[n-1-i] - '0';
}
scanf("%s",s); n = strlen(s);
for(int i = 0; i < n; ++ i)
{
b[i] = s[n-1-i] - '0';
}
if(!check(a,b)) {
swap(a,b);
printf("-");
}
sub(a,b);
}
高精度乘法
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
char s[N];
vector<int>a;
int b,n;
void mul(vector<int>&a,int b)
{
int t = 0;
for(int i = 0; i < a.size(); ++ i)
{
a[i] = a[i]*b + t;
t = a[i]/10;
a[i] %= 10;
}
while(t)
{
a.push_back(t%10); t/=10;
}
}
void out(vector<int>a)
{
if(!a.back()) {
printf("0\n");
return;
}
for(int i = a.size()-1; i >= 0; -- i) printf("%d",a[i]);
printf("\n");
}
int main()
{
scanf("%s",s); n = strlen(s);
for(int i = 0; i < n; ++ i)
{
a.push_back(s[n-1-i] - '0');
}
scanf("%d",&b);
mul(a,b);
out(a);
}
高精度除法
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
char s[N];
vector<int>a;
int b,n;
void mul(vector<int>&a,int b)
{
int t = 0;
for(int i = 0; i < a.size(); ++ i)
{
a[i] = a[i]*b + t;
t = a[i]/10;
a[i] %= 10;
}
while(t)
{
a.push_back(t%10); t/=10;
}
}
int div(vector<int>&a,int b)
{
int t = 0, p;
for(int i = a.size()-1; i >=0; --i )
{
a[i] += t * 10;
t = a[i]%b;
a[i] = a[i]/b;
}
while(a.size() > 1 && !a.back()) a.pop_back();
return t;
}
void out(vector<int>a)
{
if(!a.back()) {
printf("0\n");
return;
}
for(int i = a.size()-1; i >= 0; -- i) printf("%d",a[i]);
printf("\n");
}
int main()
{
scanf("%s",s); n = strlen(s);
for(int i = 0; i < n; ++ i)
{
a.push_back(s[n-1-i] - '0');
}
scanf("%d",&b);
int t = div(a,b);
out(a);
printf("%d\n",t);
}
转载请注明原文地址:https://blackberry.8miu.com/read-34133.html