Skip to content

Instantly share code, notes, and snippets.

@MagallanesFito
Last active September 12, 2019 21:34
Show Gist options
  • Save MagallanesFito/0190dc7c5c3e400ff4883bd38faa27bf to your computer and use it in GitHub Desktop.
Save MagallanesFito/0190dc7c5c3e400ff4883bd38faa27bf to your computer and use it in GitHub Desktop.
Karatsuba Algorithm for efficiently multiplication of integers VS Naive Multiplication Algorithm
/*This is a helper function, returns 10**exp
*/
public static int power_ten(int exp){
if(exp == 0) return 1;
else return 10*power_ten(exp-1);
}
/*
Given two strings, representing integers, calculate their product.
This works approximately quadratic time, considering the number of digits in both s1 and s2 are equal.
*/
public static int naive_multiplication(String s1,String s2){
int k = 0;
int sum = 0;
int count = 0;
int final_sum = 0;
int n = s2.length() -1;
for(int i=s2.length()-1;i>=0;i--){
sum = 0;
int shift = n - i;
k = 0;
for(int j=s1.length()-1;j>=0;j--){
int d2 = s2.charAt(i) - '0';
int d1 = s1.charAt(j) - '0';
int m = d1*d2 + count;
sum = sum + (m%10*power_ten(k));
if(m>10){
count = m/10;
}
else{
count = 0;
}
k++;
}
final_sum = final_sum + (sum*power_ten(shift));
}
return final_sum;
}
/*
This works in O(log_2 3) = O(1.58), not too much for small integers, but considerably better
with big integers
*/
public static int karatsuba_multiplication(String s1,String s2){
//Single digit
if(s1.length() == 1 && s2.length() == 1){
return (s1.charAt(0) - '0')*(s2.charAt(0) - '0');
}
int n = Math.max(s1.length(), s2.length());
int m = n/2;
int x = Integer.parseInt(s1);
int pow_m = power_ten(m);
Integer x_h = x / pow_m;
Integer x_l = x % pow_m;
int y = Integer.parseInt(s2);
Integer y_h = y/pow_m;
Integer y_l = y%pow_m;
int a = karatsuba_multiplication(x_h.toString(),y_h.toString());
int d = karatsuba_multiplication(x_l.toString(),y_l.toString());
Integer x_f = x_h+x_l;
Integer y_f = y_h+y_l;
int e = karatsuba_multiplication(x_f.toString(),y_f.toString()) - a-d;
Integer finale = (a*(power_ten(2*m)) + e*power_ten(m) + d);
return finale;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment