Karatsuba algorithm乘法问题

Divide and Conquer


Implement the Karatsuba algorithm for Multiplication problem in your favourite language,

and compare the performance with quadratic grade-school method.


Karatsuba algorithm乘法问题_第1张图片

只需要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:

Karatsuba algorithm乘法问题_第2张图片

代码如下:

#! /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


 
  

你可能感兴趣的:(算法设计与分析)