俄羅斯農民乘法的Python實現

《計算機程序的構造和解析》第31頁提到一種有時被稱做「俄羅斯農民的方法」的乘法運算,是基於加、加倍和折半的算法。譯言上有詳細解釋(http://article.yeeyan.org/view/57492/28201)。python

下面的代碼是基於Python的實現, 在 timeit.Timer().timeit(1) 中測試了25位數字的乘法,耗時176 us (微秒)。算法

# coding:utf-8
# in Python 2.7.5
import timeit
def russian(x,y):
	L = []
	s = 0
	while y > 0:
		L.append( (x,y) )
		x *= 2
		y /= 2
		
	#print x,y
	for x,y in L:
		#print x, y
		if y % 2:
			s += x
	return s
	
def russian2(x,y):
	L = []
	s = 0
	while y > 0:
		L.append( (x,y) )
		x <<=1
		y >>=1
		
	#print x,y
	for x,y in L:
		#print x, y
		if y % 2:
			s += x
	return s
	
def russian3(n,m):
    L = {}
    s = 0
    while m > 0:
        L[m] = n
        #m /= 2
        #n *= 2
        m >>= 1
        n <<= 1
    for key in L:
        #print key,
        if key%2 ==1:
            s += L[key]
         
    return s

def test():
	return russian3(3206542342234343411233123,2534542342234343411233123)
	#return  (3206542342234343411233123 * 2534542342234343411233123)
'''
if __name__ == '__main__':
	import timeit
	print timeit.timeit('test()', setup="from __main__ import test")
'''
#print test()

#begin=time.time()
t1=timeit.Timer("test()","from __main__ import test")
print t1.timeit(1)
#end=time.time()
#print (end-begin)
相關文章
相關標籤/搜索