My Weblog

Blog about programming and math

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.
Karatsuba algorithm use only 3 multiplication to multiply two 2 digit number so how do we avoid the 4th multiplication.
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)
				int[] ret=new int[2*a.length];
				for(int i=0;i<a.length;i++)
				 	for(int j=0;j<b.length;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];
			int[] ab_l=Mul(a_l,b_l);

			int[] ab_r=Mul(a_r,b_r);
			for(int i=0;i<n/2;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++)
			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.


June 23, 2009 - Posted by | Programming

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: