Karatsuba Algorithm
•The basic step of Karatsuba's algorithm
is a formula that allows one to compute
the product of two large
numbers x and y using
•three multiplications of smaller
numbers, each with about half as many
digits as x or y,
•plus some additions and digit shifts.
Karatsuba Algorithm
Karatsuba Algorithm
• Using Divide and Conquer, we can multiply
two integers in less time complexity.
• We divide the given numbers in two
halves.
• X = Xl * 2 ^ n/2 + Xr
[Xl and Xr contain leftmost and rightmost
n/2 bits of X]
• Y = Yl * 2 ^ n/2 + Yr
[Yl and Yr contain leftmost and rightmost
n/2 bits of Y]
Karatsuba Algorithm
• If x = 1234
• y = 4321
• how do we represent them using 2 digit
numbers?
Karatsuba Algorithm
• The product XY can be written as following.
XY = (Xl* 2^n/2 + Xr)(Yl*2^n/2 + Yr)
= 2^n XlYl + 2^n/2 (XlYr + XrYl) + XrYr
• There are four multiplications of size n/2,
• so we basically divided the problem of size n
into four sub-problems of size n/2.
• But that doesn’t help because solution of
recurrence
• T(n) = 4T(n/2) + O(n) is O(n^2)
Karatsuba Algorithm
• The tricky part of this algorithm is to
change the middle two terms to some other
form so that only one extra multiplication
would be sufficient.
• The following is tricky expression for
middle two terms.
• XlYr + XrYl = (Xl + Xr)(Yl + Yr) - XlYl- XrYr
• So the final value of XY becomes
• XY = 2^n XlYl + 2^n/2 * [(Xl + Xr)(Yl + Yr) -
XlYl - XrYr] + XrYr
Karatsuba Algorithm
• With above trick, the recurrence
becomes
• T(n) = 3T(n/2) + O(n)
• and solution of this recurrence is
O(n ^ log23) = O(n ^1.59).
Karatsuba Algorithm
Karatsuba Algorithm
Karatsuba Algorithm: Time
complexity