High-precision addition and high-precision multiplication of positive integers (c + +)
The addition operation is as follows:
//High-precision additionstringAddstringAstringb) {//Make sure a >= b if(A.size () <b.size ()) { stringtemp =A; A=b; b=temp; } intLen1 = A.size (), len2 =b.size (); //A, b prefix 0, such as a = 12345, B = 678, after 0 a = 012345,b = 0000678.A ='0'+A; for(inti =0; I <= len1-len2; i++) b ="0"+b; stringsum; for(inti =0; I <= len1; i++) sum + ='0'; intc =0;//Rounding for(inti = len1; I >=0; i--) { intT = (A[i]-'0') + (B[i]-'0') +C; Sum[i]+ = t%Ten; C= t/Ten; } //if the highest bit is 0, the highest bit is removed if(sum[0] =='0') sum = SUM.SUBSTR (1, Sum.size ()); returnsum;}
Multiplication is based on the addition operation, the main idea of multiplication is to transform multiplication into addition.
Please look at the following equation first:
12345*4=12345+12345+12345+12345
12345*20=123450*2
12345*24=12345*20+12345*4
The equation (1) shows that multiple digits multiply by one number and can be done directly using addition.
The equation (2) shows that the number of multiple-digit multiplicative shapes, such as d*10n, can be converted to multiple-digit multiplication by a number to be processed.
The equation (3) shows that the number of multiple digits multiplied by multiple digits can be converted to the sum of several "multiple-digit multiplicative shapes such as d*10n and multiple-digit multiplication by one number".
Therefore, the multi-digit multiply multi-digit can finally be realized by adding all of them.
The implementation code is as follows:
//High-precision multiplication: Using high-precision additionstringMultistringAstringb) {if(A.size () <b.size ()) { stringtemp =A; A=b; b=temp; } intLen1 = A.size (), len2 =b.size (); stringProduct ="0"; for(inti = len2-1; I >=0; i--) { if(I < len2-1) A + ="0"; stringtemp =A; if(B[i] = ='0') temp ="0"; Else for(intK =1; K < b[i]-'0'; k++) Temp=Add (temp, a); Product=Add (product, temp); } returnproduct;}
Subtraction and division to be continued ...
High-progress addition and high-precision multiplication