【干货】高精度模板【加,减,乘,快速幂】

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define N 1010
 4 #define LL long long
 5 #define fu(a,b,c) for(int a=b;a<=c;++a)
 6 #define fd(a,b,c) for(int a=b;a>=c;--a)
 7 const int Base=10000;
 8 struct Big{
 9   int len,w,t[N];
10   Big(){len=w=1;memset(t,0,sizeof(t));}
11 }ans;
12 Big change(int a){
13   Big c;c.len=0;
14   if(a<0)c.w=-1;
15   a=abs(a);
16   while(a)c.t[++c.len]=a%Base,a/=Base;
17   return c;
18 }
19 void print(Big c){
20   if(c.w==-1)printf("-");
21   printf("%d",c.t[c.len]);
22   fd(i,c.len-1,1)printf("%04d",c.t[i]);
23   printf("
");
24 }
25 bool unsigned_cmp(Big a,Big b){//只比较数字大小
26   if(a.len>b.len)return 1;
27   if(a.len<b.len)return 0;
28   fd(i,a.len,1){
29     if(a.t[i]>b.t[i])return 1;
30     if(a.t[i]<b.t[i])return 0;
31   }
32   return 1;
33 }
34 Big unsigned_add(Big a,Big b){
35   Big c;c.len=max(a.len,b.len);
36   fu(i,1,c.len)c.t[i]=a.t[i]+b.t[i];
37   fu(i,1,c.len){
38     if(c.t[i]>Base){
39       c.t[i]-=Base;
40       c.t[i+1]++;
41       if(i==c.len)c.len++;
42     }
43   }
44   return c;
45 }
46 Big unsigned_sub(Big a,Big b){
47   Big c;c.len=max(a.len,b.len);
48   fu(i,1,c.len)c.t[i]=a.t[i]-b.t[i];
49   fu(i,1,c.len){
50     if(c.t[i]<0){
51       c.t[i]+=Base;
52       c.t[i+1]--;
53     }
54   }
55   fd(i,c.len,1){
56     if(!c.t[i])c.len--;
57     else break;
58   }
59   return c;
60 }
61 Big add(Big a,Big b){
62   Big c;
63   if(unsigned_cmp(b,a))swap(a,b);
64   if(a.w==1&&b.w==1)c=unsigned_add(a,b),c.w=1;
65   if(a.w==1&&b.w==-1)c=unsigned_sub(a,b),c.w=1;
66   if(a.w==-1&&b.w==1)c=unsigned_sub(a,b),c.w=-1;
67   if(a.w==-1&&b.w==-1)c=unsigned_add(a,b),c.w=-1;
68   return c;
69 }
70 Big sub(Big a,Big b){b.w=0-b.w;return add(a,b);}
71 Big mul(Big a,Big b){
72   Big c;c.w=a.w*b.w;
73   c.len=a.len+b.len-1;
74   fu(i,1,a.len)
75     fu(j,1,b.len)
76       c.t[i+j-1]+=a.t[i]*b.t[j];
77   fu(i,1,c.len){
78     if(c.t[i]>Base){
79       c.t[i+1]+=c.t[i]/Base;
80       c.t[i]%=Base;
81       if(i==c.len)c.len++;
82     }
83   }
84   return c;
85 }
86 Big fast_pow(Big a,int b){
87   Big ans;ans.t[1]=1;
88   if((b&1)&&a.w==-1)ans.w=-1;
89   while(b){
90     if(b&1)ans=mul(ans,a);
91     b>>=1;
92     a=mul(a,a);
93   }
94   return ans;
95 }
96 int main(){
97   return 0;
98 }
原文地址:https://www.cnblogs.com/dream-maker-yk/p/9676239.html