-其它- A+B|A-B|A*B Problem

当long long不够用时,就得用高精度了!

高精度加法

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
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char a1[500001],b1[500001];
int a[500001],b[500001],c[500001],x,lenc,la,lb,i;
int main(){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
gets(a1);
gets(b1);
la=strlen(a1);
lb=strlen(b1);
for(i=0;i<=la-1;i++){
a[la-i]=a1[i]-'0';
}
for(i=0;i<=lb-1;i++){
b[lb-i]=b1[i]-'0';
}
lenc=1;
x=0;
while(lenc<=la||lenc<=lb){
c[lenc]=a[lenc]+b[lenc]+x;
x=c[lenc]/10;
c[lenc]%=10;
lenc++;
}
c[lenc]=x;
if(c[lenc]==0) lenc--;
for(i=lenc;i>=1;i--) cout<<int(c[i]);
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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main(){
int a[10001],b[10001],c[10001],la,lb,lc,i;
char n[10001],n1[10001],n2[10001];
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
cin>>n1>>n2;
if(strlen(n1)<strlen(n2)||(strlen(n1)==strlen(n2)&&strcmp(n1,n2)<0)){
strcpy(n,n1);
strcpy(n1,n2);
strcpy(n2,n);
cout<<"-";
}
la=strlen(n1);
lb=strlen(n2);
for(i=0;i<=la-1;i++){
a[la-i]=int(n1[i]-'0');
}
for(i=0;i<=lb-1;i++){
b[lb-i]=int(n2[i]-'0');
}
i=1;
while(i<=la||i<=lb){
if(a[i]<b[i]){
a[i]+=10;
a[i+1]--;
}
c[i]=a[i]-b[i];
i++;
}
lc=i;
while((c[lc]==0)&&(lc>1)) lc--;
for(i=lc;i>=1;i--) cout<<c[i];
cout<<endl;
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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//A*B problem.cpp
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a1[2006],b1[2006];
int a[2006]={0},b[2006]={0},c[20000050]={0},lena,lenb,lenc,i,j,x;
int main(){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
scanf("%s",a1);
scanf("%s",b1);
lena=strlen(a1);
lenb=strlen(b1);
for(i=0;i<lena;i++){
a[lena-i]=a1[i]-'0';
}
for(i=0;i<lenb;i++){
b[lenb-i]=b1[i]-'0';
}
for(i=1;i<=lena;i++){
x=0;
for(j=1;j<=lenb;j++){
c[i+j-1]=a[i]*b[j]+x+c[i+j-1];
x=c[i+j-1]/10;
c[i+j-1]%=10;
}
c[i+lenb]=x;
}
lenc=lena+lenb;
while(c[lenc]==0&&lenc>1){
lenc--;
}
for(i=lenc;i>=1;i--){
cout<<c[i];
}
cout<<endl;
return 0;
}
文章作者: RiverFun
文章链接: https://stevebraveman.github.io/blog/2018/08/21/8/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 RiverFun

评论