Skip to content

Instantly share code, notes, and snippets.

@Sowailam
Sowailam / KaratsubaMultiplication.java
Last active January 24, 2021 19:03
Karatsuba Algorithm in Java
public class KaratsubaMultiplication {
public static long performeKaratsuba(long x, long y){
if(x < 10 || y < 10) return x*y;
// get the length of longest number
int maxBase = (int) Math.max(Math.log10(x), Math.log10(y)) + 1;
int halfMax = Math.round(maxBase/2);
//int halfMax = (maxBase/2) + (maxBase%2); // also valid
long a = x / (int) Math.pow(10, halfMax);
long b = x % (int) Math.pow(10, halfMax);