Learning this blog article: https://www.cnblogs.com/-Ackerman/
First we look at the addition of large numbers
Can be understood, first added together, then the carry, of course, we are all here with a string to store, look at the code to understand the
#include <. bits / STDC H ++> the using namespace STD; String BigAdd ( String S1, String S2) { String Anser; int LEN1 s1.length = (); // Get the character length int LEN2 = s2.length (); int num1 [ 100 ] = { 0 }, num2 [ 100 ] = { 0 }; // this can be solved preamble 0 for ( int I = 0 ; I <LEN1; I ++ ) num1 [LEN1 -I- . 1 ] S1 = [I] - ' 0 '; // reverse order to add num1, that num1 is in accordance with a ten hundred. . . for ( int I = 0 ; I <LEN2; I ++ ) num2 [LEN2 -I- . 1 ] = S2 [I] - ' 0 ' ; int lenth = LEN1> LEN2? LEN1: LEN2; for ( int I = 0 ; I <lenth; I ++ ) { [I] num1 + = [I] num2; // you adder num1 [I + . 1 ] + = num1 [I] / 10 ; // carry, after small bits into a large position num1 [ I]% = 10 ; // save the remainder after carried to the small bit } IF (! Num1 [lenth]) // go preamble 0
lenth-- ; for ( int I = lenth; I> = 0 ; i-- ) { Anser + num1 = [I] + ' 0 ' ; } return Anser ; // the results returned } int main () { String A, B; the while (CIN >> A >> B) { COUT << BigAdd (A, B) << endl; } return 0 ; }
If you can understand large numbers of addition, multiplication of large numbers and so it is in fact carry on the same principle, but need to understand how to calculate multiplication
I 98 * 23, for example, answer = 3 * 8 * 9 * 10 + 3 + 2 + 2 * 10 * 8 * 9 * 10 * 10, you can verify yourself I write right
Law of multiplication: j-th bit number that is obtained by multiplying the number of the i-th bit and a number of other, must be accumulated to the result of the i + j bits. Here i, j is from right to left, starting from 0 count.
That is: ans [i + j] = a [i] * b [j];
#include <. bits / STDC H ++> the using namespace STD; #define MAX 100 int X [MAX + 10 ], Y [MAX + 10 ], Z [MAX * 2 + 10 ], I, J; String BigMultiply ( String A, String B) { int LEN1 = a.length (); int LEN2 = to b.length (); string Anser; for (J = 0 , I = len1- . 1 ; I> = 0 ; i--) // string characters into digital, and store reverse X [J ++] = A [I] - ' 0' ; // here added a more convenient J is equivalent to the addition of large numbers of the above [len-i-1], see you readily appreciated that for (J = 0 , I = len2- . 1 ; I> = 0 ; I- - ) Y [J ++] = B [I] - ' 0 ' ; for ( int I = 0 ; I <LEN1; I ++ ) { for ( int J = 0 ; J <LEN2; J ++ ) { Z [I + J] + = X [I] * Y [J]; // } } for ( int I = 0 ; I < 2 * MAX; I ++) { IF (Z [I]> = 10 ) // binary { Z [I + . 1 ] + = (Z [I] / 10 ); Z [I] = Z [I]% 10 ; } } for (I * MAX = 2 ; I> 0 ; i--) // remove prefix 0 { IF (Z [I] == 0 ) Continue ; the else BREAK ; } for (; I> = 0 ; i--) // reverse output anser + = z [i] +'0'; return anser; } int main() { string a,b; while(cin>>a>>b) { cout<<BigMultiply(a,b)<<endl; } return 0; }