大数的高精度算法

高精度加法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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;
}

 

高精度减法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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;
}

高精度乘法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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);
}

  

高精度除法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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;
}

 

posted @   一统天下。  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示