Multiplication of large numbers, addition of large numbers, subtraction of large numbers Java version

Source: Internet
Author: User

Question: multiply (add, subtract) two very large numbers)

This topic can be implemented using methods in the biginteger class in Java. Otherwise, use the following method.

Multiply a large number: Assume there are two big numbers, A and B, and the digits are A and B, respectively. We can see that the number of digits C in the final result must be smaller than or equal to a + B According to the usual method of multiplication. We can give a simple example to illustrate that 99*999 = 98901, the final result is five digits (A + B ). Next we will refer to 98*765 = 74970 to see how each bit in the result is obtained, the last digit 0 is the last digit of A, the last digit 8 and the last digit 5 of B, except for 10 digits, the second-last 7 of the result is the product of the last 5 of 9 and B of A. 45 is the product of the last 8 and the last 6 of B. and 93, then add the carry 4 of the previous digit to get 97, and then get 7 in addition to 10 ...... The final result can be obtained by proceeding in sequence.

The following is a summary of the rule: the product of the J-th bits in A and B will be stored in the I + J bits in the result (both I and J are counted from the back to the Front ), therefore, we can perform the computation of every bit in the result first, and carry out the computation after all computation. In order to calculate I and j from 0, we first reverse the string a and B, and then start from 0 during the computation. The specific procedure is as follows:

Public static void bignumbersimplemulti (string F, string s) {system. out. print ("multiplication: \ n" + F + "*" + S + "="); // obtain the first character to determine whether it is a signed Char signa = f. charat (0); char signb = S. charat (0); char Sign = '+'; If (Signa = '+' | signa = '-') {Sign = Signa; F = f. substring (1) ;}if (signb = '+' | signb = '-') {If (Sign = signb) {Sign = '+ ';} else {Sign = '-';} s = S. substring (1);} // flip a large number and convert it into a character array ch Ar [] A = new stringbuffer (f ). reverse (). tostring (). tochararray (); char [] B = new stringbuffer (s ). reverse (). tostring (). tochararray (); int Lena =. length; int lenb = B. length; // calculates the final maximum length of int Len = Lena + lenb; int [] result = new int [Len]; // calculates the result set for (INT I = 0; I <. length; I ++) {for (Int J = 0; j <B. length; j ++) {result [I + J] + = (INT) (a [I]-'0') * (INT) (B [J]-'0') ;}// processing result set. If it is greater 10 is the carry of the forward digit, except 10 for (INT I = 0; I <result. length; I ++) {If (result [I]> 10) {result [I + 1] + = Result [I]/10; result [I] % = 10 ;}} stringbuffer sb = new stringbuffer (); // This field is used to identify whether there is a front 0, boolean flag = true; For (INT I = len-1; I> = 0; I --) {If (result [I] = 0 & flag) {continue;} else {flag = false;} sb. append (result [I]);} If (! SB. tostring (). equals ("") {If (Sign = '-') {sb. insert (0, sign) ;}} else {sb. append (0);} // returns the final result system. out. println (sb. tostring ());}

Add large numbers:It is similar to multiplication. The difference is only the length of the result set, and its value is the length of a long string plus one. The Code is as follows:

Public String bignumberadd (string F, string s) {// flip two strings and convert them to an array char [] A = new stringbuffer (f ). reverse (). tostring (). tochararray (); char [] B = new stringbuffer (s ). reverse (). tostring (). tochararray (); int Lena =. length; int lenb = B. length; // calculate the length of two long strings. Int Len = Lena> lenb? LENA: lenb; int [] result = new int [Len + 1]; for (INT I = 0; I <Len + 1; I ++) {// if the current I exceeds one of them, replace it with 0 and add int aint = I <Lena? (A [I]-'0'): 0; int bint = I <lenb? (B [I]-'0'): 0; Result [I] = aint + bint;} // processing result set. If the value is greater than 10, it is carried forward, except 10 for (INT I = 0; I <result. length; I ++) {If (result [I]> 10) {result [I + 1] + = Result [I]/10; result [I] % = 10 ;}} stringbuffer sb = new stringbuffer (); // This field is used to identify whether a front 0 exists. If yes, do not store Boolean flag = true; for (INT I = Len; I> = 0; I --) {If (result [I] = 0 & flag) {continue;} else {flag = false ;} SB. append (result [I]);} return sb. tostring ();}

Subtraction of large numbers:The subtraction of large numbers is similar to the addition of large numbers, but positive and negative values must be determined.

Public static string bignumbersub (string F, string s) {system. out. print ("subtraction:" + F + "-" + S + "= "); // flip the string and convert it into a character array char [] A = new stringbuffer (f ). reverse (). tostring (). tochararray (); char [] B = new stringbuffer (s ). reverse (). tostring (). tochararray (); int Lena =. length; int lenb = B. length; // find the maximum length int Len = Lena> lenb? LENA: lenb; int [] result = new int [Len]; // indicates the positive and negative char sign of the result = '+ '; // determine the positive and negative if (Lena <lenb) {Sign = '-';} else if (Lena = lenb) {int I = Lena-1; while (I> 0 & A [I] = B [I]) {I --;} if (a [I] <B [I]) {Sign = '-';} // calculates the result set. If the final result is positive, A-B; otherwise, B-A for (INT I = 0; I <Len; I ++) {int aint = I <Lena? (A [I]-'0'): 0; int bint = I <lenb? (B [I]-'0'): 0; If (Sign = '+') {result [I] = aint-bint ;} else {result [I] = Bint-aint ;}// if one of the result sets is smaller than zero, borrow one from the first one and add 10 to the base. In fact, it is equivalent to performing the subtraction for (INT I = 0; I <result. length-1; I ++) {If (result [I] <0) {result [I + 1]-= 1; Result [I] + = 10 ;}} stringbuffer sb = new stringbuffer (); // if the final result is a negative value, the negative number is placed at the beginning, and the positive number does not need if (Sign = '-') {sb. append ('-');} // determines whether there is a front 0 Boolean flag = true; For (INT I = len-1; I> = 0; I --) {If (result [I] = 0 & flag) {continue;} else {flag = false;} sb. append (result [I]);} // if no value exists in the final result set, the two values are equal, and 0 if (sb. tostring (). equals ("") {sb. append ("0");} // return value system. out. println (sb. tostring (); return sb. tostring ();}

In the above calculation process, there are several notes: When a large number is added, the positive and negative numbers are not judged. If they are all positive numbers, they can be calculated by adding positive numbers, if it is a positive or a negative, it can be converted to a large integer to subtract from each other. You can save the two negative numbers and then add them together.

Related Article

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.