The multiplication and addition of the basic arithmetic algorithm for the super-long integer

Source: Internet
Author: User

written calculation multiplication:for M-bit and n-bit inputs, the traditional multiplication requires m*n-th basic multiplication, i.e. the algorithm complexity is O (). When we multiply with paper and pens, we multiply each bit of the multiplier by multiplying each bit of the multiplier with the carry of the previous column to produce an appropriate shift of the intermediate result, and then add the intermediate results of the rows to get the final result of the multiplication, for example, the process of calculating 189*34 in 10 binary is as follows:

The operation process of written calculation multiplication


The algorithm is calculated according to the above procedure, but it is best to perform the internal multiplication and addition in parallel, that is, to calculate the intermediate result of each row and add the line to the final result, which can save a lot of steps and avoid the space overhead and memory management operation of the intermediate result. This simple optimization can improve the efficiency to some extent. The pseudo code of this algorithm is as follows:

Input: Large integer x, y with N and t binary digits, respectively

Output: Product of the B-binary

1. I from 0 to n+t-1, place WI = 0

2. I from 0 to T

2.1 J from 0 to N

Calculate wi+j=wi+j + xj * Yi

If the wi+j is not less than the carry value,

The current intermediate value representation is reformatted

3. Return

Since the product of two 16 bits will exceed the maximum number that 16 bits can represent, we know that a 32-bit number can preserve the product of two 16-bit numbers completely, and the pseudo-code above uses a 32-bit to preserve the product of two 16-bits and the result of two words. Here is a discussion of its security (whether it will overflow): The maximum result of the above expression calculation is (216-1) * (216-1) + (216-1), after simplification is 232-216, less than a maximum of 32 digits, so a 32-digit can save the result of the expression without overflow. The program does not lose precision.

There is a special kind of multiplication in multiplication-self-squared. It is natural to use a general method of calculation for this kind of multiplication, but it can be done in a much quicker way, using a single traversal of integers to solve the result that the general multiplication requires nesting loops two times to process, because the two multipliers of the square are "symmetric", Take a (A1A2A3A4) as an example: each bit of multiplication will have a corresponding bit repeat operation once, for example, A1*A4 will be executed two times, and the corresponding product results in the same result position accumulated. Therefore, the efficiency of the self-squared algorithm is higher than that of the general multiplication.

/* multiply operation */int Mulhbint (Hbigint *product, Hbigint *bia, Hbigint *bib) {hbigint bit;//calculation results first saved in temporary variable register un_short *pworda = bia->    Pbigint;register un_short *pwordb = bib->pbigint;register Un_short *PPRD = Null;long result = 0, i = 0, j = 0; Initializes a temporary large integer variable if (result = Inithbint (&bit,bia->length + bib->length))! = return_ok_bint) RETURN result; Bit.length = bia->length + bib->length;bit.sign = (Bia->sign = = bib->sign)? 1:-1; The same number is positive, the number is negative PPRD = Bit.pbigint;for (i=0; i<bia->length; ++i) {//the product for (j=0; j<bib->length; ++j) is calculated as a traditional paper-pen multiplication method {Pprd[i+j] = Pprd[i+j] + pworda[i] * pwordb[j];//if exceeding the unit length can represent the maximum value (in this case, 2<<16), one time format is processed if (Pprd[i+j] >> bit_ Pre_word) Formathbint (&bit);}} Formathbint (&bit); Trimhbint (&bit);//Remove High-level invalid 0extendHBInt (product,bit.length); Assignhbint (Product, &bit);d eletehbint (&bit); Clear temporary variable RETURN return_ok_bint;} 

Written Calculation Division:

This algorithm simulates the form of written calculation division and is deformed. Based on the characteristics of written calculation division, we know that the most important and difficult step is the estimation of the quotient. We do the division, according to dividend and the divisor of the highest number of trial quotient, this algorithm is also used this way. In order to improve the speed of the trial, the trader that tries to use cannot be starting from 1 until I,i meet. This operation uses the binary lookup method to test the quotient, thus improving the speed.

In addition to the trial business, another difficulty is to the divisor of the bit alignment. In most operations, the number of bits in the divisor is less than the divisor, so it is necessary to move the divisor to the left before the trial is done, that is, the person is the multiplier (Bn) of the widening divisor. As for the number of left shifts, it is necessary to compare the highs to determine the following rules:

Input: Large integer x (divisor), Y (dividend) of two B-ary (bits m, N)

x=m1m2. Mm,y=n1n2...nn

Output: Left shift number L

1. By default M < N, initialize L=N-M

2. Compare the high-level portion of two numbers:

2.1 Comparison between M1 and N1

If M1 > N1 are L=L-1

If M1 = N1 then set i from 0. L

If Mi > ni are l=l-1

Otherwise, end the loop

3. Return to L

/* Division operation a Dividend B divisor c quotient D remainder */int divhbint (hbigint *a, Hbigint *b, Hbigint *c, Hbigint *d) {hbigint ta,tb,tc,temp,tc_1; Temp variable long result=0,first=1,middle=0,last=0;un_short mark=0;long len_ta,len_tb,len,i;int re;if (0 = = B->length | | (1 = = B->length && 0 = = b->pbigint[0])) return-1; Divisor cannot be 0//divisor is 1, quotient equals dividend, remainder is 0if (1 = = B->length && 1 = = B->pbigint[0]) {assignhbint (c,a); Setzerohbint (d); Hbi_add_int (d,0); return return_ok_bint;} Re = Comparehbint (A, B), if ( -1 = = re) {//divisor is greater than dividend, quotient is 0, remainder is dividend setzerohbint (c); Assignhbint (d,a); return return_ok_bint;} if (0 = = re) {//divisor equals dividend, quotient is 1, remainder is 0setZeroHBInt (c); Setzerohbint (d); Hbi_add_int (c,1); Hbi_add_int (d,0); return Return_ok_ BINT;} Initialize temporary variable inithbint (&ta,initial_bint); Inithbint (&tb,initial_bint); Inithbint (&tc,initial_bint); Inithbint (&temp,initial_bint); Inithbint (&tc_1,initial_bint); Len_ta=ta.length;len_tb=ta.length;len=len_ Ta-len_tb;i=0;assignhbint (&ta,a);//Assign Assignhbint (&tb,b) to temporary variable, hbi_add_int (&tc,1);//initial quotient is 1Extendhbint (&temp,ta.length);//Extended temporary variable length extendhbint (&tc_1,ta.length);//dichotomy Trial quotient calculation while (Comparehbint (& TA,B) > 0) {//guarantee TA is greater than B cycle len_ta=ta.length;len_tb=tb.length;len=len_ta-len_tb;i=0;mark=0;if (Ta.pbigint[len_ta-1] <= Tb.pbigint[len_tb-1]) {while (I&LT;LEN_TB) {if (Ta.pbigint[len_ta-1-i] < tb.pbigint[len_tb-1-i]) {mark= Ta.pbigint[len_ta-1];len--;i++;break;} else i++;}} Left_shift_word (&tb,len);//The divisor is left shifted, so that it has the same number Left_shift_word with dividend (&tc,len);//quotient simultaneous left shift Result=mark*carry_ radix+ta.pbigint[len_ta-1-i];first=1;last= Result/tb.pbigint[len_tb-1+len] + 1;//The upper limit of the binary lookup method middle= (Last+first)/2 + 1 ;//binary find median for (; (First < last) && (first! = middle); ) {//Use the binary lookup method to try the Assignhbint (&AMP;TEMP,&AMP;TB); Hbi_mul_radix (&temp,middle); if ( -1 = = Comparehbint (&ta,& temp)) Last=middle;else first=middle;middle= (Last+first)/2;} Assignhbint (&AMP;TEMP,&AMP;TB); Hbi_mul_radix (&temp,middle); Subhbint (&ta,&ta,&temp);//divisor-divisor *  Shang Hbi_mul_radix (&tc,middle); Get the ADDHB of the business you are tryingInt (&AMP;TC_1,&AMP;TC_1,&AMP;TC);//Setzerohbint the quotient (&AMP;TC);     The value of the temporary depositary is 0HBI_ADD_INT (&tc,1);//1 Setzerohbint (&temp) for the temporary variable of the quotient; Assignhbint (&tb,b);} if (Comparehbint (&ta,b) = = 0) {hbi_add_int (c,1); Setzerohbint (d);} else {if (c!=null) assignhbint (c,&tc_1);// The quotient if (d!=null) Assignhbint (D,&AMP;TA) of the division operation is obtained;//the remainder of the division operation}//Reclaim the temporary variable Space deletehbint (&AMP;TA); Deletehbint (&AMP;TB);d eletehbint (&AMP;TC);d eletehbint (&tc_1);d eletehbint (&temp); return return_ok_bint;}




The multiplication and addition of the basic arithmetic algorithm for the super-long integer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.