高精度

Template001
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include <bits/stdc++.h>
using namespace std;

int compare(string str1,string str2)
{
if (str1.length()>str2.length()) return 1;
else if (str1.length()<str2.length()) return -1;
else return str1.compare(str2);
}

string add(string str1,string str2)
{
string ans;
int cf=0,temp;
int len1=str1.length();
int len2=str2.length();
if (len1<len2) for (int i=1;i<=len2-len1;i++) str1="0"+str1;
else for (int i=1;i<=len1-len2;i++) str2="0"+str2;
len1=str1.length();
for (int i=len1-1;i>=0;i--)
{
temp=str1[i]-'0'+str2[i]-'0'+cf;
cf=temp/10;
temp%=10;
ans=char(temp+'0')+ans;
}
if (cf!=0) ans=char(cf+'0')+ans;
return ans;
}

string sub(string str1,string str2)
{
string ans;
int tmp=str1.length()-str2.length(),cf=0;
for (int i=str2.length()-1;i>=0;i--)
{
if(str1[tmp+i]<str2[i]+cf)
{
ans=char(str1[tmp+i]-str2[i]-cf+'0'+10)+ans;
cf=1;
}
else
{
ans=char(str1[tmp+i]-str2[i]-cf+'0')+ans;
cf=0;
}
}
for (int i=tmp-1;i>=0;i--)
{
if(str1[i]-cf>='0')
{
ans=char(str1[i]-cf)+ans;
cf=0;
}
else
{
ans=char(str1[i]-cf+10)+ans;
cf=1;
}
}
ans.erase(0,ans.find_first_not_of('0'));
return ans;
}

string mul(string str1,string str2)
{
string ans;
int len1=str1.length();
int len2=str2.length();
string tempstr;
for(int i=len2-1;i>=0;i--)
{
tempstr="";
int temp=str2[i]-'0';
int t=0;
int cf=0;
if (temp!=0)
{
for (int j=1;j<=len2-1-i;j++) tempstr+="0";
for (int j=len1-1;j>=0;j--)
{
t=(temp*(str1[j]-'0')+cf)%10;
cf=(temp*(str1[j]-'0')+cf)/10;
tempstr=char(t+'0')+tempstr;
}
if (cf!=0) tempstr=char(cf+'0')+tempstr;
}
ans=add(ans,tempstr);
}
ans.erase(0,ans.find_first_not_of('0'));
return ans;
}

void div(string str1,string str2,string &quotient,string &residue)
{
quotient=residue="";
if (str2=="0")
{
quotient=residue="ERROR";
return;
}
if (str1=="0")
{
quotient=residue="0";
return;
}
int res=compare(str1,str2);
if (res<0)
{
quotient="0";
residue=str1;
return;
}
else if (res==0)
{
quotient="1";
residue="0";
return;
}
else
{
int len1=str1.length();
int len2=str2.length();
string tempstr;
tempstr.append(str1,0,len2-1);
for (int i=len2-1;i<len1;i++)
{
tempstr=tempstr+str1[i];
tempstr.erase(0,tempstr.find_first_not_of('0'));
if (tempstr.empty()) tempstr="0";
for (char ch='9';ch>='0';ch--)
{
string str,tmp;
str=str+ch;
tmp=mul(str2,str);
if (compare(tmp,tempstr)<=0)
{
quotient=quotient+ch;
tempstr=sub(tempstr,tmp);
break;
}
}
}
residue=tempstr;
}
quotient.erase(0,quotient.find_first_not_of('0'));
if (quotient.empty()) quotient="0";
}