# My Weblog

## Karatsuba Multiplication

We can multipy two n digit number in O(n^2) using our conventional multiplicaton method.We can make it fast by a constant using arithmetic on higher bases like 10^9 because our computer takes almost constant time in multiplying two number as long as it fits into computer memory(long long operations are slightly costly than int ).Can we do something better than this? One approach is Karatsuba algorithm. Let we have two n bit Numbers A and B.Here n must be power of 2 otherwise pad 0.
A=(a_l*10^n+a_r)
B=(b_l*10^n+b_r)
A*B=(a_l*b_l)*10^2n+(a_l*b_r+b_l*a_r)*10^n+a_r*b_r
Karatsuba algorithm use only 3 multiplication to multiply two 2 digit number so how do we avoid the 4th multiplication.
(a_l*b_r+b_l*a_r)=(a_l+a_r)*(b_l+b_r)-a_l*b_l-a_r*b_r.
The complexity of algorithm is T(n)=3T(n/2)+Theta(n)
From Masters Theorme , solution of this recurrence is O(n^log(3/2)) i.e. O(n^1.57).

My implimentation in Java

```class Karat
{

int[] Mul(int[] a,int[] b)
{
if(a.length<=2)
{
int[] ret=new int[2*a.length];
for(int i=0;i<a.length;i++)
{
for(int j=0;j<b.length;j++)
{
ret[i+j]+=a[i]*b[j];

}
}
return ret;
}

int n=a.length;
int[] b_l=new int[n/2];int[] b_r=new int[n/2];int[] a_l=new int[n/2];int[] a_r=new int[n/2];
System.arraycopy(a,n/2,a_l,0,n/2);
System.arraycopy(a,0,a_r,0,n/2);
System.arraycopy(b,n/2,b_l,0,n/2);
System.arraycopy(b,0,b_r,0,n/2);
int[] ab_l=Mul(a_l,b_l);

int[] ab_r=Mul(a_r,b_r);
for(int i=0;i<n/2;i++)
{
a_l[i]+=a_r[i];
b_l[i]+=b_r[i];
}

int[] ab_lr=Mul(a_l,b_l);
for(int i=0;i<n;i++)ab_lr[i]-=ab_l[i]+ab_r[i];

int[] ret=new int[2*n];
for(int i=0;i<n;i++)
{
ret[i]+=ab_r[i];
ret[i+n/2]+=ab_lr[i];
ret[i+n]+=ab_l[i];
}

return ret;
}
}
```

Some details of Implimentation . If you want to multiply 1234 to 5678 store the numbers in reverse order in array.From initial call array a ={4,3,2,1} and b={8,7,6,5}. Normalize the result dividing by 10 from left to right.The base condition you can increase the limit like 16, 32 , 64 or 128.