Using divide-and-conquer method to realize multiplication, addition and subtraction of large numbers (Java implementation)

Source: Internet
Author: User
Tags string format

Large number multiplication is the problem of polynomial multiplication, the product C (x) of a (x) and B (x), the complexity of the Naïve solution O (n^2), the basic idea is to write the polynomial a (x) and B (x)

A (x) =a*x^m+b
B (x) =c*x^m+d

Where a,b,c,d is the polynomial of x.
Then a (x) *b (x) = (AC) *x^2m+ (AD+BC) *x^m+bd
by ad+bc= (a+b) (c+d)-AC-BD
The original 4 multiplication and 1 additions were replaced by 3 multiplication and 2 subtraction, which reduced one multiplication operation.
Apply the same method to the ABCD multiplication.

(The above content is excerpted from the Internet)

The following code is implemented in Java:

 Packagecom.kyy.sf; Public classBigInteger { PublicBigInteger () {}//The basic idea is to write the polynomial a (x) and B (x)//A (x) =a*x^m+b//B (x) =c*x^m+d//where a,b,c,d is the polynomial of x. //then A (x) *b (x) = (AC) *x^2m+ (AD+BC) *x^m+bd//by Ad+bc= (a+b) (c+d)-AC-BD//string Simulation multiplication Operation         Public Staticstring Mut (string x, string y) {//deep++;//Console.WriteLine ("-" + Deep + "-");String negative = ""; //x, y are positive or negative        if(X.startswith ("-") && Y.startswith ("-"))                || (!x.startswith ("-") &&!y.startswith ("-"))) {x= X.replaceall ("-", "" "); Y= Y.replaceall ("-", "" "); Negative= ""; }//x, Y, one positive and one negative        Else if(X.startswith ("-") &&!y.startswith ("-"))                || (!x.startswith ("-") && Y.startswith ("-"))) {x= X.replace ("-", "" "); Y= Y.replace ("-", "" "); Negative= "-"; }        //if the length is equal to 9, multiply directly and return to the line.         if(x.length () = = 1 && y.length () = = 1) {            //Calculate Product            intTMP = (integer.parseint (x) *integer.parseint (y)); if(TMP = = 0) {                returnTMP + ""; } Else {                returnNegative +tmp; }        }        //the ABCD in the formulaString A, B, C, D; if(x.length () = = 1) {a= "0"; b=x; } Else {            if(X.length ()% 2! = 0) {x= "0" +x; } A= x.substring (0, X.length ()/2); b= X.substring (X.length ()/2); }        if(y.length () = = 1) {C= "0"; D=y; } Else {            if(Y.length ()% 2! = 0) {y= "0" +y; } C= y.substring (0, Y.length ()/2); D= Y.substring (Y.length ()/2); }        //value by maximum number of digits to determine 0 number of complements        intn = x.length () >= y.length ()?x.length (): Y.length ();        String T1, T2, T3; //recursive invocation, which calculates the value based on the formula. String AC =Mut (A, c); String BD=Mut (b, D); T1=Mut (Sub (A, b), Sub (d, c)); T2=Add (Add (T1, AC), BD); T3= Add (Add (Power10 (AC, N), Power10 (T2, N/2)), BD). ReplaceAll ("^0+",                ""); if(T3 = = "")            return"0"; returnNegative +T3; }    Private Staticstring Add (string x, string y) {if(X.startswith ("-") &&!y.startswith ("-"))) {            returnSub (Y, X.replaceall ("^-", "" ")); } Else if(!x.startswith ("-") && Y.startswith ("-"))) {            returnSub (x, Y.replaceall ("^-", "" ")); } Else if(X.startswith ("-") && Y.startswith ("-"))) {            return"-" + Add (X.replaceall ("^-", ""), Y.replaceall ("^-", "" ")); }        if(X.length () >y.length ()) {y= Format (y, X.length (), "0"); } Else{x= Format (x, Y.length (), "0"); }        int[] sum =New int[X.length () + 1];  for(inti = X.length ()-1; I >= 0; i--) {            intTmpsum = Integer.parseint (X.charat (i) + "")                    + Integer.parseint (Y.charat (i) + "") + Sum[i + 1]; if(Tmpsum >= 10) {Sum[i+ 1] = tmpsum-10; Sum[i]= 1;//denotes rounding}Else{sum[i+ 1] =tmpsum; }} StringBuilder returnvalue=NewStringBuilder ();  for(inti:sum)        {returnvalue.append (i); }        if(Sum[0] = = 1) {            returnreturnvalue.tostring (); } Else {            returnReturnvalue.replace (0, 1, ""). toString (); }    }    //string emulation subtraction Operation    Private Staticstring Sub (string x, string y) {//x is positive, Y is positive        intFlag =Checkbigger (x, y); if(flag = = 0) {            return"0"; } Else if(Flag = =-1) {String tmp=y; Y=x; X=tmp; }        //guaranteed x>=y.y = Format (y, X.length (), "0");//y complement 0 and x align        int[] difference =New int[X.length ()];  for(inti = X.length ()-1; I >= 0; i--) {            inttmpdifference; Tmpdifference= Integer.parseint (X.charat (i) + "")                    -Integer.parseint (Y.charat (i) + "") +Difference[i]; if(Tmpdifference < 0) {tmpdifference+ = 10; Difference[i-1] =-1;//denotes rounding} Difference[i]=tmpdifference; } StringBuilder returnvalue=NewStringBuilder ();  for(inti:difference)        {returnvalue.append (i); } String RV= Returnvalue.tostring (). ReplaceAll ("^0+", "" "); if("". Equals (RV)) {            return"0"; }        if(Flag = =-1) {RV= "-" +RV; }        returnRV; }    //Compare Size    Private Static intCheckbigger (string x, string y) {if(X.length () >y.length ()) {            return1; } Else if(X.length () <y.length ()) {            return-1; } Else {             for(inti = 0; I < x.length (); i++) {                if(X.charat (i) >Y.charat (i)) {                    return1; } Else if(X.charat (i) <Y.charat (i)) {                    return-1; }            }            return0; }    }    //data Pre-fill 0    Private Staticstring format (String str,intLen, String Fu) {Len= Len-str.length ();  for(inti = 0; i < Len; i++) {str= Fu +str; }        returnstr; }    //Analog Shift     Public StaticString Power10 (String num,intN) { for(inti = 0; I < n; i++) {num+ = "0"; }        returnnum; }     Public Static voidMain (string[] args) {String x= "93859048059849086850986804750894758903278473894578397598475984784857487584758094875890475984955624146039530798877974 "; String y= "224343444859408590475847538946";                System.out.println (Mut (x, y)); System.out.println (Mut ("1111111111", "1111111111")); }}

Using divide-and-conquer method to realize multiplication, addition and subtraction of large numbers (Java implementation)

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.