Java large number addition and subtraction multiplication __java

Source: Internet
Author: User

Addition and subtraction is the process of simulating written calculation, including rounding and borrow. If the multiplication uses the written calculation process, the time complexity is O (n2). Existing Karatsuba algorithm , time complexity of O (nlog23) .

The principle is as follows:

Like 1234*5678, first split the numbers into 12, 34 and 56, 78.
Make z=34*78
r1=12*56*10000
R2= (12*78+34*56) *100
= ((12+34) * (56+78) -34*78) *100
This would be a little less multiplication, because 34*78 has been counted in the last step.
Final results =r1+r2+z
If the number is still large after the first split, it can be recursively called and split until the number of splits is small enough. The code is as follows:

Package test;

Import Java.math.BigInteger;
        public class Bignumbercalculater {public static void main (string[] args) {String num1 = "987654321";

        String num2 = "123456789";
        System.out.println ("plus =" + addstring (NUM1, num2));
        System.out.println ("minus =" + minusstring (NUM1, num2));

        System.out.println ("multiply =" + karatsubamultiply (NUM1, num2));
        BigInteger a = new BigInteger (NUM1);

        BigInteger B = new BigInteger (num2);
        System.out.println ("plus =" + A.add (b));
        System.out.println ("minus =" + a.subtract (b));
        System.out.println ("multiply =" + a.multiply (b));
        System.out.println ("except =" + A.divide (b));
    System.out.println ("take the remainder =" + a.mod (b));
        }//Large number subtraction public static string minusstring (string num1, String num2) {int len1 = Num1.length ();
        int len2 = Num2.length ();
        if (Num1.equals (num2)) {return "0";
        Boolean positive = true; if (Len1 < Len2 | | (len1= = Len2 && Num1.compareto (num2) < 0)) {positive = false;
            String tmp = NUM1;
            NUM1 = num2;
            NUM2 = tmp;
            int temp = LEN1;
            Len1 = Len2;
        Len2 = temp;
        String result = "";
        int i = len1-1, j = len2-1;

        int A, B, sum, CArray = 0;
            while (i >= 0 | | | J >= 0) {//from low to high position to do subtraction a = (i >= 0? num1.charat (i)-' 0 ': 0);
            b = (J >= 0 Num2.charat (j)-' 0 ': 0);
            sum = A-b + CArray;

            CArray = 0;
                if (Sum < 0) {//Borrow sum = 10;
            CArray =-1;
            result = (sum) + result;
            I.;
        --j; result = Result.replaceall ("^[0]+", "");//delete leading 0 return positive?
    Result: "-" + result;
        }//Large number addition public static string AddString (string num1, String num2) {int len1 = Num1.length (); IntLen2 = Num2.length ();
        if (len1 <= 0) {return num2;
        } if (len2 <= 0) {return num1;
        String result = "";
        int i = len1-1, j = len2-1;
        int A, B, sum, carry = 0;
            while (i >= 0 | | | J >= 0 | | | Carry > 0) {//Add from the bottom a = i >= 0? num1.charat (i)-' 0 ': 0; b = J >= 0?
            Num2.charat (j)-' 0 ': 0; sum = a + B + carry;
            Add by bit and carry carry = sum/10;//result = (sum%) + result;
            I.;
        --j;
    return result; }//Karatsuba large number multiplication public static string karatsubamultiply (string num1, String num2) {int len1 = Num1.len
        Gth ();
        int len2 = Num2.length ();
        int len = LEN1;
            if (Len1 < len2) {for (int i = 0; i < len2-len1; ++i) {num1 = "0" + num1;
        len = len2; } else {fort i = 0; i < len1-len2;
            ++i) {num2 = "0" + num2;
        len = len1;
        } if (len = = 0) {return "0";
        } if (len = = 1) {return string.valueof ((Num1.charat (0)-' 0 ') * (Num2.charat (0)-' 0 '));

        int mid = LEN/2;
        String x1 = num1.substring (0, mid);
        String x0 = num1.substring (mid, Len);
        String y1 = num2.substring (0, mid);

        String y0 = num2.substring (mid, Len);
        String z0 = karatsubamultiply (x0, y0);
        String z1 = karatsubamultiply (addstring (x1, x0), addstring (Y1, y0));

        String z2 = karatsubamultiply (x1, y1);
        String r1 = shiftstring (z2, 2 * (Len-mid));

        String r2 = shiftstring (minusstring (minusstring (z1, Z2), z0), len-mid);
    Return AddString (addstring (R1, R2), z0);
            ///On the right add Len 0 public static String shiftstring (string num, int len) {if (Num.equals ("0")) { return nUm
        for (int i = 0; i < len; ++i) {num = "0";
    return num;
 }
}

Java BigInteger can satisfy the various operations of any large integer, real words can be used BigDecimal, so I use biginteger to verify the results of this algorithm. The results are:

Add =1111111110
Minus =864197532
by =121932631112635269
Add =1111111110
Minus =864197532
by =121932631112635269
Except =8
Take Yu =9

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.