高精度除法——高精度除以高精度

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 int a[101],b[101],c[101],i;
 5 //输入函数 
 6 void init(int a[]){
 7     string s;
 8     cin>>s;
 9     a[0]=s.length();
10     for(i=1;i<=a[0];i++)
11         a[i]=s[a[0]-i]-'0';//减法倒序存储 
12 }
13 //输出函数
14 void print(int a[]){
15     int i;
16     if(a[0]==0){
17         cout<<0<<endl;
18         return;
19     }
20     for(i=a[0];i>0;i--)
21         cout<<a[i];
22     cout<<endl;
23     return;  //函数执行完毕回到主程序 
24 }
25 //比较函数 
26 int compare(int a[],int b[]){
27     int i;
28      if(a[0]>b[0])  
29          return 1;
30      if(a[0]<b[0])  
31          return-1;
32      for(i=a[0];i>0;i--){ //如果两数位数相等,则按位比大小 
33          if(a[i]>b[i]) 
34              return 1;
35           if(a[i]<b[i])
36               return -1;  //按位比较若该位数相同,则判断下一位 
37      }
38     return 0;//如果返回0则表示两数相等 
39 }
40 //减法模拟除法 
41 void jian(int a[],int b[]){
42     int flag,i;
43     flag=compare(a,b);
44     if(flag==0){
45         a[0]=0;
46         return;
47     }
48     if(flag==1){
49         for(i=1;i<=a[0];i++){
50             if(a[i]<b[i]){
51                 a[i+1]--;
52                 a[i]=a[i]+10;
53             }
54             a[i]-=b[i];
55         }
56         while(a[0]>0&&a[a[0]]==0)
57             a[0]--;
58         return;
59     }
60 }
61 //复制数组 
62 void numcpy(int p[],int q[],int det){
63     for(int i=1;i<=p[0];i++) 
64         q[i+det-1]=p[i];
65     q[0]=p[0]+det-1;
66     /*
67     for(int i=q[0];i>0;i--) 
68         cout<<q[i];
69     cout<<endl;   
70     打印复制后的数字,方便理解算法,此算法主要采用低位补0做减法 
71     */
72 }
73 //除法计算 
74 void chugao(int a[],int b[],int c[]){
75     int i,tmp[101];
76     c[0]=a[0]-b[0]+1;   //商的位数不超过被除数的位数-除数的位数+1 
77     for(i=c[0];i>0;i--){  //每次循环确定某位商的的值,从高位开始 
78         memset(tmp,0,sizeof(tmp));
79         numcpy(b,tmp,i);
80         while(compare(a,tmp)>=0){
81             c[i]++;
82             jian(a,tmp);
83         }
84     }
85     while(c[0]>0&&c[c[0]]==0)  
86         c[0]--;
87     return;
88 } 
89 //主函数
90 int main(){
91     init(a);
92     init(b);
93     chugao(a,b,c);
94     print(c);
95     print(a);
96     return 0; 
97 }

猜你喜欢

转载自www.cnblogs.com/Hankercat/p/10331701.html