- 揭芷沐 的博客
我的博客之代码篇
- @ 2025-8-16 15:47:39
高精度乘法
string mul(string x,string y){
int a[2010] = {},b[2010] = {},c[4010] = {},lenx = x.size(),leny = y.size();
for(int i = 0 ; i < lenx ; i ++)a[i] = x[lenx - i - 1] - '0';
for(int j = 0 ; j < leny ; j ++)b[j] = y[leny - j - 1] - '0';
for(int i = 0 ; i < lenx ; i ++){
for(int j = 0 ; j < leny ;j ++){
c[i + j] += a[i] * b[j];
c[i + j + 1] += c[i + j] / 10;
c[i + j] %= 10;
}
}
int len = lenx + leny;
while(len > 1 && c[len - 1] == 0)len -- ;
string res = "";
for(int i = len - 1; i >= 0 ;i --)res += c[i] + '0';
return res;
}
高精度加法
string add(string x,string y){
int a[1010] = {},b[1010] = {},lenx = x.size(),leny = y.size();
for(int i = lenx - 1 ; i >= 0 ; i --)a[i] = x[lenx - i - 1] - '0';
for(int i = leny - 1 ; i >= 0 ; i --)b[i] = y[leny - i - 1] - '0';
int len = max(lenx,leny);
for(int i = 0 ; i < len ; i ++){
a[i] += b[i];
a[i + 1] += a[i] / 10;
a[i] %= 10;
}
if(a[len])len ++;
string res = "";
for(int i = len - 1; i >= 0 ; i --)res += a[i] + '0';
if(res.size() == 0)return "0";
return res;
}
高精度减法
string sub(string x,string y){//计算两个高精度数字加法的结果
string ans = "";
if(x.size() < y.size() || x.size() == y.size() && x < y){
swap(x,y);
ans += "-";
}
int a[101000] = {},b[101000] = {},lenx = x.size(),leny = y.size();
//x[lenx - 1 - i] - '0'是表示把字符转换成数字
for(int i = 0 ; i < lenx ; i ++)a[i] = x[lenx - 1 - i] - '0';//倒序存储
for(int i = 0 ; i < leny ; i ++)b[i] = y[leny - 1 - i] - '0';//倒序存储
int len = max(lenx,leny);//取长度更长的数字长度
for(int i = 0 ;i < len ; i ++){
a[i] -= b[i];
if(a[i] < 0){
a[i] += 10;
a[i + 1] --;
}
}
if(a[len] == 1)len ++;//判断最高位有没有进位,有的话那么数字长度变长
for(int i = len - 1 ; i >= 0; i -- )ans += a[i] + '0';
return ans;
}
高精度除法(高精除以低精度)
struct node{
string s;
int res;
};
node divd(string a,int b){
node ans = {"",0};
for(int i = 0 ; i < a.size() ;i ++){
ans.res = ans.res * 10 + a[i] - '0';//余数和下一位结合
ans.s += ans.res / b + '0';//计算每一位商
ans.res %= b;//重新计算余数
}
while(ans.s[0] == '0')ans.s = ans.s.substr(1);
if(ans.s == "")ans.s = "0";
return ans;
}