Multiplication of large numbers and factorial
The addition, multiplication, and factorial operations of large numbers may cause overflow of results. You can convert them into strings before performing operations. Note that, traditionally, the addition and multiplication operations start from the low position. The first bit is calculated, and the second bit is carried to the high position until the highest bit. A string represents a number such as "3476". Its low number is at the maximum subscript. To be consistent with the operation in practice, you can first reverse the string, after finding the result, you can reverse the result. The next addition operation uses the inverse method, and the multiplication operation can also use similar inversion, but the multiplication operation in this article does not use inversion. The calculated result can be saved in a string or an integer array. The next addition operation stores the result in a string, multiplication and factorial Save the result in an integer array. When performing a factorial operation, each digit is stored in an integer variable, and a loop is used to multiply each digit by 2, 3, 4, 5, 6 ..., And process carry, so that the factorial of the number can be obtained.
# Include
# Include
# Include
# Include
# Include
Using namespace std; const int N = 110; void numadd (int a, int B) // Add {assert (a> 0 & B> 0 ); char * t1 = new char [100]; char * t2 = new char [100]; sprintf (t1, "% d", a); sprintf (t2, "% d", B); string oper1 (t1); string oper2 (t2); reverse (oper1.begin (), oper1.end ()); // reverse the string reverse (oper2.begin (), oper2.end (); int I = 0, j = 0; int carry = 0; // carry string res (50, '0'); int k = 0; while (k
0) res [k]-= 10; ++ k;} while (k
0) res [k]-= 10; ++ k;} while (k
0) res [k]-= 10; ++ k;} if (carry) {res [k ++] = '1';} for (I = res. size ()-1; I> = 0; -- I) if (res [I]! = '0') break; res = res. substr (0, I + 1); reverse (res. begin (), res. end (); // reverse the result to cout <
<
= 0; I --) for (j = lenb-1; j> = 0; j --) {c [I + j + 1] + = (a [I]-'0') * (B [j]-'0 '); if (c [I + j + 1]> = 10) {c [I + j] + = c [I + j + 1]/10; c [I + 1 + j] = c [I + j + 1] % 10 ;}} I = 0; while (c [I] = 0) I ++; // process the case where the maximum bit is 0 for (; I
= 0; -- I) cout <
<
<
<