大数的高精度算法
高精度加法:
#include <bits/stdc++.h>
using namespace std;
string add(string &a,string &b){
string c;
int t=0;
if(a.length()<b.length()) return add(b,a);
for(int i=0;i<a.length()||t;i++){
if(i<a.length())t+=a[i]-'0';
if(i<b.length()) t+=b[i]-'0';
c += ((t % 10) + '0');
t=t/10;
}
reverse(c.begin(),c.end());
return c;
}
int main(){
string a,b;
int len;
cin>>a>>b;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
string c=add(a,b);
cout<<c;
}
高精度减法:
#include<bits/stdc++.h>
using namespace std;
bool cmp(string a,string b){
if(a.length()!=b.length()) return a.length()>b.length();
for(int i=0;i<a.length();i++)
if(a[i]!=b[i]) return a[i]>b[i];
return true;
}
string sub(string a,string b){
string c;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
for(int i=0,t=0;i<a.length();i++){
t=(a[i]-'0')-t;
if(i<b.length()) t-=(b[i]-'0');
c+=((t+10)%10+'0');
if(t>=0) t=0;
else t=1;
}
while(c.length()>1&&c.back()=='0') c.pop_back();
reverse(c.begin(),c.end());
return c;
}
int main(){
ios::sync_with_stdio(false);
string a,b;
cin>>a>>b;
if(cmp(a,b)) cout<<sub(a,b);
else cout<<"-"<<sub(b,a);
return 0;
}
高精度乘法:
#include<bits/stdc++.h>
using namespace std;
string mul(string a, int b){
reverse(a.begin(),a.end());
string c;
int t=0;
for(int i=0;i<a.length()||t;i++){
if(i<a.length()) t+=(a[i]-'0')*b;
c+=((t%10)+'0');
t=t/10;
}
while(c.length()>1&&c.back()=='0') c.pop_back();
reverse(c.begin(),c.end());
return c;
}
int main(){
string a;
int b;
cin>>a>>b;
cout<<mul(a,b);
}
高精度除法:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string div(string &a,int b,int &r){
string c;
for(int i=0;i<a.length();i++){
r=r*10+(a[i]-'0');
c+=((r/b)+'0');
r=r%b;
}
return c;
}
int main(){
string a,c;
int b,r=0,i=0;
cin>>a>>b;
c=div(a,b,r);
if(c.length()==1) cout<<c;
else{while(c[i]=='0') i++;
if(i>=c.length()) cout<<'0';
else{for(int j=i;j<c.length();j++)
cout<<c[j];
}
}
cout<<endl<<r;
}

浙公网安备 33010602011771号