大数乘法&除法

来源:互联网 发布:b站up主 知乎 编辑:程序博客网 时间:2024/05/17 03:39
1. 大数乘法
常见解法:A * B
1)利用进位加法器的思想
①用B的最低位去乘A的每一位,闭关在计算过程中处理进位,并存储该轮结果;
②在用B的次位去乘A 的每一位,计算中间结果,并存储数据;
③循环计算B的每一位乘A的每一位的结果,并计算之和。

2)计算结果中每一位数出现的个数
①依次用B的每一位去乘A中的每一位,但保存的结果不为中间结果,而为个十百千位出现的次数;
②将每轮中间结果中的位出现的个数来计算最终结果。

本算法使用第二种思想。
//字符串转化为int//src:源字符串//number:目的数数组//length:src长度void string2int(char * src, int * number, int length);void string2int(char * src, int * number, int length){ //define the buffer to store the data char * str = (char *)malloc(sizeof(char)*(length+1)); memset(str, '\0', length+1); memcpy(str, src, length);/* puts(str);*/ strrev(str);/* puts(str);*/ //transfer string to int //int temp = *number; //原有的数据不为零时,也需要考虑 int i=0; for (i=0; i<length; i++) {  //temp *= 10;  //原有数据为字符'A',顾需要减去'0'  number[i] += (int)(str[i] - '0'); } //return the transfer number //*number = temp; //clear the dynamic memory free(str); str = NULL;}//大数相乘//乘数:numsA,numsB//长度:lenA, lenBvoid BigNumberMultiplication(int * numsA, int lenA, int * numsB, int lenB, int * results); void BigNumberMultiplication(int * numsA, int lenA, int * numsB, int lenB, int * results){ int i, j; //multi procedure for (i=0; i<lenB; i++) {  for (j=0; j<lenA; j++)  {   results[i+j] += numsA[j] * numsB[i];  //the i,j place number multi, //and the result is on the i+j place   } } //process the result for (i=0; (i<200); i++) {  if (results[i]>=10)  //the low place to the high place, if the low number is >= 10  {   results[i+1] += results[i] /10;   results[i] %= 10;  } }}



2. 大数相除
算法思想:
1)采样进位加法器的思想
①取得被除数中与除数位数相同的数,作为一个中间被除数;
②利用该中间被除数去除以除数,商作为结果的最高位,余数保留;
③取得被除数的下一位,并与②中的余数组成一个与除数相同位数的中间被除数;
④循环调用②和③,直到算出结果。

算法实现:
//字符转化为int////////////////////////////////////////////////////////////////////////////number:上层数据遗留,类似于加法进位器//string: 12345//int   : number*10+1)*10)+2)*10+2)*10+4)*10+5////char * src: 字符串数组//int length:字符串的长度//int * number://      1)作为输入源:代表数据原始的数组,为上一次数据的进位;//      2)作为输出源:代表数据最终的结果//////////////////////////////////////////////////////////////////////////void string2int(char * src, int * number, int length){ //define the buffer to store the data char * str = (char *)malloc(sizeof(char)*(length+1)); memset(str, '\0', length+1); memcpy(str, src, length); //transfer string to int int temp = *number;  //原有的数据不为零时,也需要考虑 int i=0; for (i=0; i<length; i++) {  temp *= 10;  temp += (int)(str[i] - '0'); }  //return the transfer number *number = temp; //clear the dynamic memory delete str; str = NULL;}//中间被除数计算结果int calculateResult(int *dividend, int divisor){ int temp = *dividend; int resultStep = temp/divisor; temp = temp%divisor; *dividend = temp;  //返回余数至下次使用 return resultStep; //返回商值}//循环调用计算大数除for ( i += divisorlen; i<dividendlen; i++) {  //求得中间被除数的商值  result[j++] = calculateResult(&temp, divisorint);  //printf("%d---%d\n", j, result[j-1]);  //选取下一次的被除数:向后选取一个字符  string2int(&dividend[i], &temp, 1); }











0 0