[其它] A+B|A-B|A*B Problem
当long long不够用时,就得用高精度了!
高精度加法
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 char a1[500001],b1[500001]; 6 int a[500001],b[500001],c[500001],x,lenc,la,lb,i; 7 int main(){ 8 memset(a,0,sizeof(a)); 9 memset(b,0,sizeof(b)); 10 memset(c,0,sizeof(c)); 11 gets(a1); 12 gets(b1); 13 la=strlen(a1); 14 lb=strlen(b1); 15 for(i=0;i<=la-1;i++){ 16 a[la-i]=a1[i]-'0'; 17 } 18 for(i=0;i<=lb-1;i++){ 19 b[lb-i]=b1[i]-'0'; 20 } 21 lenc=1; 22 x=0; 23 while(lenc<=la||lenc<=lb){ 24 c[lenc]=a[lenc]+b[lenc]+x; 25 x=c[lenc]/10; 26 c[lenc]%=10; 27 lenc++; 28 } 29 c[lenc]=x; 30 if(c[lenc]==0) lenc--; 31 for(i=lenc;i>=1;i--) cout<<int(c[i]); 32 return 0; 33 }
高精度减法
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 int main(){ 6 int a[10001],b[10001],c[10001],la,lb,lc,i; 7 char n[10001],n1[10001],n2[10001]; 8 memset(a,0,sizeof(a)); 9 memset(b,0,sizeof(b)); 10 memset(c,0,sizeof(c)); 11 cin>>n1>>n2; 12 if(strlen(n1)<strlen(n2)||(strlen(n1)==strlen(n2)&&strcmp(n1,n2)<0)){ 13 strcpy(n,n1); 14 strcpy(n1,n2); 15 strcpy(n2,n); 16 cout<<"-"; 17 } 18 la=strlen(n1); 19 lb=strlen(n2); 20 for(i=0;i<=la-1;i++){ 21 a[la-i]=int(n1[i]-'0'); 22 } 23 for(i=0;i<=lb-1;i++){ 24 b[lb-i]=int(n2[i]-'0'); 25 } 26 i=1; 27 while(i<=la||i<=lb){ 28 if(a[i]<b[i]){ 29 a[i]+=10; 30 a[i+1]--; 31 } 32 c[i]=a[i]-b[i]; 33 i++; 34 } 35 lc=i; 36 while((c[lc]==0)&&(lc>1)) lc--; 37 for(i=lc;i>=1;i--) cout<<c[i]; 38 cout<<endl; 39 return 0; 40 }
高精度乘法
1 //A*B problem.cpp 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 using namespace std; 6 char a1[2006],b1[2006]; 7 int a[2006]={0},b[2006]={0},c[20000050]={0},lena,lenb,lenc,i,j,x; 8 int main(){ 9 memset(a,0,sizeof(a)); 10 memset(b,0,sizeof(b)); 11 memset(c,0,sizeof(c)); 12 scanf("%s",a1); 13 scanf("%s",b1); 14 lena=strlen(a1); 15 lenb=strlen(b1); 16 for(i=0;i<lena;i++){ 17 a[lena-i]=a1[i]-'0'; 18 } 19 for(i=0;i<lenb;i++){ 20 b[lenb-i]=b1[i]-'0'; 21 } 22 for(i=1;i<=lena;i++){ 23 x=0; 24 for(j=1;j<=lenb;j++){ 25 c[i+j-1]=a[i]*b[j]+x+c[i+j-1]; 26 x=c[i+j-1]/10; 27 c[i+j-1]%=10; 28 } 29 c[i+lenb]=x; 30 } 31 lenc=lena+lenb; 32 while(c[lenc]==0&&lenc>1){ 33 lenc--; 34 } 35 for(i=lenc;i>=1;i--){ 36 cout<<c[i]; 37 } 38 cout<<endl; 39 return 0; 40 }