Last active
May 25, 2018 19:53
-
-
Save viniru/1311542729e815636a8fb470602468a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigInteger; | |
class KaratsubaMulti{ | |
public static BigInteger compute(String x,String y) | |
{ | |
int n = 0; | |
int n1 = x.length(); | |
int n2 = y.length(); | |
if(n1>=n2)n=n2; | |
else n = n1; | |
if(n == 1) | |
{ | |
BigInteger a = new BigInteger(x); | |
BigInteger b = new BigInteger(y); | |
return a.multiply(b); | |
} | |
int nm = n/2; | |
String a = x.substring(0,n1-nm); | |
String b = x.substring(n1-nm,n1); | |
String u = y.substring(0,n2-nm); | |
String v = y.substring(n2-nm,n2); | |
BigInteger r1 = compute(a,u); | |
BigInteger r2 = compute(b,v); | |
BigInteger r3 = compute((new BigInteger(a)).add(new BigInteger(b)).toString(),(new BigInteger(u)).add(new BigInteger(v)).toString()).subtract(r1).subtract(r2); | |
String xx = ""; | |
for(int i=0;i<nm;i++) | |
xx=xx+"0"; | |
String s1 = r1.toString().concat(xx).concat(xx); | |
String s3 = r3.toString().concat(xx); | |
return((new BigInteger(s1)).add(r2).add(new BigInteger(s3))); | |
} | |
public static void main(String args[]) | |
{ | |
String a = "12345"; | |
String b = "123"; | |
System.out.println(compute(a,b)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please let me know if there any better way to do this . Since , with my logic I have to inter-convert between big integer and string hectic number of times and this adds to complexity.For your information , inbuilt multiply() function for big integers in java uses karatsuga multiplication .