带图详解 【算法模板】高精度模板( 二 )


#includeusing namespace std;const int N = 10000;#define LENGTH 1001void HighMul(string x, stringy) {//与加法一样int a[1000] = { 0 }, b[1000] = { 0 }, c[1000] = { 0 }, len;for (int i = 0; i < x.size(); i++)a[i] = x[x.size() - i - 1] - '0';for (int i = 0; i < y.size(); i++)b[i] = y[y.size() - 1 - i] - '0';//与加法不同的是,长度最大变成两个数的长度之和len =x.size()+ y.size();for (int i = 0; i < x.size(); i++) {for (int j = 0; j < y.size(); j++) {c[i + j] += a[i] * b[j];//两数相乘,存到对应位置c[i + j + 1] += c[i + j] / 10;//把进位加到前面一位上c[i + j] %= 10;//取模存0-9的数}}while ((c[len - 1] == 0) && (len > 1)) len--;for (int i = len - 1; i >= 0; i--)printf("%d", c[i]);printf("\n"); }
四、高精度除法 4.1、高精度除以低精度
for (int i = 0; i < x.size(); i++) {c[i] = (tmp * 10 + a[i]) / y;tmp = (tmp * 10 + a[i]) % y;}
算法原理用手写,说不清楚 。
#includeusing namespace std;const int N = 10000;#define LENGTH 1001void HighDiv(string x, int y) {int a[LENGTH]={0}, b[LENGTH]={0}, c[LENGTH]={0};for (int i = 0; i < x.size(); i++) {a[i] = x[i] - '0';}int tmp = 0;for (int i = 0; i < x.size(); i++) {c[i] = (tmp * 10 + a[i]) / y;tmp = (tmp * 10 + a[i]) % y;}int cnt = 0;while (c[cnt] == 0 && cnt < x.size())cnt++;for (int i = cnt; i < x.size(); i++)cout << c[i];}
4.2、高精度除以高精度
int compare(int a[], int b[])//比较a和b的大小关系,若a>b则为1,a b[0]) return 1;//a的位数大于b则a比b大 if (a[0] < b[0]) return -1;//a的位数小于b则a比b小 for (i = a[0]; i > 0; i--)//从高位到低位比较 {if (a[i] > b[i]) return 1;if (a[i] < b[i]) return -1;}return 0;//各位都相等则两数相等 。}void numcpy(int p[], int q[], int n)//复制p数组到q数组从det开始的地方{for (int i = 1; i <= p[0]; i++) q[i + n - 1] = p[i];q[0] = p[0] + n - 1;}void jian(int a[], int b[])//计算a=a-b{int flag, i;flag = compare(a, b);//调用比较函数判断大小 if (flag == 0) { a[0] = 0; return; }//相等 if (flag == 1)//大于{for (i = 1; i <= a[0]; i++){if (a[i] < b[i]) { a[i + 1]--; a[i] += 10; }//若不够减则向上借一位 a[i] -= b[i];}while (a[0] > 0 && a[a[0]] == 0) a[0]--;//修正a的位数 return;}}void HighDiv(string x, string y) {int a[LENGTH], b[LENGTH], c[LENGTH];memset(a, 0, sizeof(a));memset(b, 0, sizeof(b));memset(c, 0, sizeof(c));a[0] = x.length();for (int i = 1; i <= a[0]; i++)a[i] = x[a[0] - i] - '0';b[0] = y.length();for (int i = 1; i <= b[0]; i++)b[i] = y[b[0] - i] - '0';int tmp[101];c[0] = a[0] - b[0] + 1;for (int i = c[0]; i > 0; i--) {memset(tmp, 0, sizeof(tmp));numcpy(b, tmp, i);while (compare(a, tmp) >= 0) {c[i]++; jian(a, tmp); }}while (c[0] > 0 && c[c[0]] == 0)c[0]--;for (int i = c[0] ; i > 0; i--)printf("%d", c[i]);printf("\n");}