Divide and Conquer
Implement the Karatsuba algorithm for Multiplication problem in your favourite language,
and compare the performance with quadratic grade-school method.
只需要3次乘法,6次加法,2次移位,复杂度T(n)=3T(n/2)+cn=O(n^(lg3/lg2))=O(n^1.585)
grade school算法复杂度T(n)=4T(n/2)+cn=O(n^2)
以13*34为例:
13=1101,34=100010
n=4:
xh=11,xl=01,yh=1000,yl=10
13*14=xhyh*2^n+(p-xhyh-xlyl)*2^n/2+xlyl
input:
999999999
9999999999
output:
代码如下:
<pre name="code" class="python">#! /usr/bin/env python
# coding:utf8
__author__ = 'yangrui'
import sys
sys.setrecursionlimit(10000000)
def Multiply(x, y):
n = (min(len(bin(x)), len(bin(y)))-2)/2*2 #对于二进制位数为奇数的-1
if x <= 2 or y <= 2:
return x * y
xh = x >> n/2
xl = x - (xh << n/2)
yh = y >> n/2
yl = y - (yh << n/2)
xhyh = Multiply(xh, yh)
xlyl = Multiply(xl, yl)
p = Multiply(xh + xl, yh + yl)
result = (xhyh << n) + (p - xhyh - xlyl << n/2) + xlyl
return result
if __name__ == '__main__':
x = 999999999
y = 9999999999
result = Multiply(x, y)
print result
print x*y