Design and Analysis of Algorithms
Divide and Conquer
(Karatsuba’s Fast Multiplication)
Dr. D. P. Acharjya
Professor, SCOPE
Office: SJT Annex 201E
Email: [email protected]
1/9/2024 Dr. D. P. Acharjya 1
Naïve Approach of Multiplication
Consider two integers a and b
Convert the integers into binary strings of same
length.
Let two integers be a = 12 and b = 10
The binary representation is given as:
a = 12 = 1100 and b = 1010
a b = 1100 1010
The output = 120 = 1111000
9 January 2024 Dr. D. P. Acharjya 2
Continued …
Number of multiplications = 16 = 42
If there are n bits, The computing time = (n2)
9 January 2024 Dr. D. P. Acharjya 3
Karatsuba’s Fast Multiplication
Consider two integers a and b
Divide both the integers into two equal parts such as
a = a1a2 and b = b1b2
Compute A = a1b1
Compute B = a2b2
Compute C = (a1 + a2) (b1 + b2)
Compute D = C – A – B
The product ab = bn A + bn/2 D + B
Where b is the base of the integer and n is the length
of the integers.
9 January 2024 Dr. D. P. Acharjya 4
Computing Time
Let the length of two integers a and b be n.
Length of a1, a2, b1, and b2 be (n/2)
A = a1b1 Computing Time = T(n/2)
B = a2b2 Computing Time = T(n/2)
C = (a1 + a2) (b1 + b2) Computing Time = T(n/2)
D = C – A – B Computing Time = constant
ab =bn A + bn/2 D + B Computing Time = Constant
The recurrence relation is
T(n) = 3T(n/2) + k
9 January 2024 Dr. D. P. Acharjya 5
Continued …
9 January 2024 Dr. D. P. Acharjya 6
Continued …
The general multiplication takes (n2) whereas
Karatsuba’s multiplication takes time (n1.58) and hence
runs faster.
The multiplication algorithm also works for binary
numbers.
1/9/2024 Dr. D. P. Acharjya 7
Numerical Illustration
Consider two integers a = 41 and b = 42
Therefore, 41 = a1a2 and 42 = b1b2
a1= 4, a2=1 and b1= 4, b2=2
A = a1b1 = 4 4=16
B = a2b2 = 1 2 =2
C = (a1 + a2) (b1 + b2) = (4+1) (4+2)=30
D = C – A – B = 30 – 16 – 2 =12
ab = bn A + bn/2 D + B = 102 16 + 101 12 + 2
= 1600 + 120 + 2 = 1722
Here, n = 2 (length of a and b) and b = base of decimals =10
1/9/2024 Dr. D. P. Acharjya 8
Note
If the length of numbers is not even, the add 0
(zeros) at the left side of the numbers to make
even length.
For numbers with length > 2, the algorithm is to
be applied recursively.
For example: let a =312 and b =408
Thus a = a1a2= 312 = 0312; a1= 03 and a2=12
b = b1b2= 408 = 0408; b1= 04 and b2=08
Solve recursively.
1/9/2024 Dr. D. P. Acharjya 9