On this topic, I'll talk about high-precision multiplication, here are the three functions to calculate multiplication, the first function is a char type, the second is a two array of type int, not converted to a number, the third is more optimized, with a array-b array back into array a inside
Function 1 idea: to first convert the char type to the number of int type, direct each number-' 0 ' can realize the conversion of char type to int type.
① record the length of array A, array B, and put it in the first place
② each phase multiplication, using a number to record the carry (initial value is 0), each phase multiplication, plus carry, deposited in the corresponding position of the C array, each carry to be re-assigned value
③ finally remember to remove the highest bit of 0, and the length of the C array to the first position (C[0])
The code is as follows:
1 voidMulCharStra[],CharStrb[],intC[])//High-precision operation of positive integers a*b---> C2 {3 intA[maxlength],b[maxlength];4 intI,j,x,lenc;5Memset (A,0,sizeof(a));//test a length6memset (b,0,sizeof(b));//Test B length7Memset (c,0,sizeof(c));//Test C Length8Init (stra,a);//a converts to a number9Init (STRB,B);//b convert to digitalTen for(i=1; i<=a[0];i++) One { Ax=0;//indicate carry, record - for(j=1; j<=b[0];j++)//It's important to be here - { thec[i+j-1]+=a[i]*b[j]+x;//each phase multiply, plus carry in C array -x=c[i+j-1]/Ten;//x re-assigned to carry -c[i+j-1]=c[i+j-1]%Ten;//1-bit reserved - } +c[i+b[0]]=x;//indicates carry (higher rounding to C) - } +lenc=a[0]+b[0];//the length of C is the length of the a+b. A while(c[lenc]==0&&lenc>1) lenc--;//Remove excess 0 on high atc[0]=Lenc; -}
Function 2 idea: This function and function 1 is not much different, but the incoming array type is not the same, this function does not have to convert the string array into a digital array, the direct calculation can
The code is as follows:
1 voidMUL2 (intA[],intB[],intC[])//High-precision operation of positive integers a*b---> C2 {3 intI,j,x,lenc;4Memset (c,0,sizeof(c));5 for(i=1; i<=a[0];i++)6 {7x=0;//denotes rounding8 for(j=1; j<=b[0];j++)9 {Tenc[i+j-1]=c[i+j-1]+a[i]*b[j]+x; Onex=c[i+j-1]/Ten; Ac[i+j-1]=c[i+j-1]%Ten; - } -c[i+b[0]]=x;//indicates carry (higher rounding to C) the } -lenc=a[0]+b[0];//the length of C is the length of the a+b. - while(c[lenc]==0&&lenc>1) lenc--;//Remove excess 0 on high -c[0]=Lenc; +}
High-precision Computing topic 3-multiplication (the multiplication operation)