文章目录
- 1. 大数加法
- 2. 大数幂运算
- 3.大数求余
废话不多说,直接上代码。
1. 大数加法
string getCountAdd(string a, string b){string c = "";int bit = -1; //判断是否进位 -1为否,其他的是进位数int i = a.length()-1; ///获得a字符串长度intt j = b.length()-1; ///获得b字符串长度//第一种情况 两者都处理完了while (i != -1 && j != -1){int t1 = a[i] - 48; int t2 = b[j] - 48;///没有进位if (bit == -1){if (t1 + t2 >= 10){int d = (t1 + t2) % 10;c.insert(0, 1, d + 48);bit = (t1 + t2) / 10;}else{c.insert(0, 1, t1 + t2 + 48);}}///有进位else存在{if (t1 + t2 + bit >= 10){int d = (t1 + t2 + bit) % 10;c.insert(0, 1, d + 48);bit = (t1 + t2 + bit) / 10;}else{c.insert(0, 1, t1 + t2 + bit + 48);bit = -1;}}i--;j--;}//第二种情况 前者处理while (i == -1 && j != -1){int t2 = b[j] - 48;if (bit == -1){c.insert(0, 1, b[j]);}else{if (t2 + bit >= 10){int d = (t2 + bit) % 10;c.insert(0, 1, d + 48);bit = (t2 + bit) / 10;}else{c.insert(0, 1, t2 + bit + 48);bit = - 1;}}j--;}///第三种情况 后者处理while (i != -1 && j == -1){int t1 = a[i] - 48;if (bit == -1){c.insert(0, 1, a[i]);}else{if (t1 + bit >= 10){int d = (t1 + bit) % 10;c.insert(0, 1, d + 48);bit = (t1 + bit) / 10;}else{c.insert(0, 1, t1 + bit + 48);bit = -1;}}i--;}///最后判断是否有进位if (bit != -1){c.insert(0, 1, bit + 48);}bit = -1;return c;}
2. 大数幂运算
string getCountExp(int a, int b){string a1 = to_string(a);int i = a1.length()-1;//a最后下角标//m位数*n位数长度不超过m+n位数string temp = a1; //temp一直在改变string temp_2 = "0";int bitcount = 0; ////判断当前位数int bit = -1;///判断进位string是否存在 * arr = new string[a1.length()];///保存每次计算的数字 arr_i = 0;for (int x = 1; x < b; x++)///几次方就会循环几次{while (i != -//乘数的位数{///temp * a1int t1 = a1[i] - 48;int j = temp.length() - 1;///temp的最后下角标for (int z = 0; z < bitcount; z++){arr[arr_i].insert(0, 1, '0');}while (j != -1)///temp的位数{int t2 = temp[j] - 48;if (bit == -1)///判断是否有进位{if (t1*t2 >= 10){int d = (t1*t2) % 10;arr[arr_i].insert(0, 1, d + 48);int d_2 = (t1*t2) / 10;bit = d_2;}else{ int d = t1*t2;arr[arr_i].insert(0, 1, d + 48);}}else{if (t1*t2)+bit >= 10){int d = (t1*t2) + bit) % 10;arr[arr_i].insert(0, 1, d + 48);int d_2 = (t1*t2) + bit) / 10;bit = d_2;}else{int d = (t1*t2) + bit;arr[arr_i].insert(0, 1, d + 48);bit = -1;}}j--;}if (bit != -1){arr[arr_i].insert(0, 1, bit + 48);bit = -1;}///走完一圈//计算每个位数,最后加///temp_2=temp_2+arr[arr_i];temp_2 = getCountAdd(temp_2, arr[arr_i]);bitcount++;arr_i++;i--;}bitcount = 0;temp = temp_2;temp_2 = "0";//temp_2 = "0";for (int z = 0; z < arr_i; z++){arr[z] = "";}arr_i = 0;i = a1.length() - 1;//a的最后下角标记}return temp;}
3.大数求余
int getCountMod(string a, int b){int bit = -1; //判断是否需要进位/比如4255%5int i = 0;while (i < a.length()){int t1 = a[i] - 48;if (bit == -1){if (t1%b > 0){bit = t1%b;}}else{if (((bit * 10) + t1) % b>=0){bit = ((bit * 10) + t1) % b;}}i++;}if (bit != -1){return bit;}else{return 0;}return 0;}