Russian Peasant Multiplication

July 26th, 2009 by Charles Ma Leave a reply »

Interesting way to multiply numbers by hand.

This is a simple python program that takes 2 arguments and shows the steps of this multiplication technique.

#!/usr/bin/python
from os import sys
def russianPeasant(num1, num2, cache):
   cache[num1] = num2
   if num1 == 1:
      return
   return russianPeasant(num1>>1, num2<<1, cache)

def printResult(cache):
   sum = 0
   for key in reversed(sorted(cache.keys())):
      if key%2 == 1:
         sum += cache[key]
         print(str(key) + ': ' + str(cache[key]))
      else:
         print('' + str(key) + ' ' + str(cache[key]) + '')
   print("------------\n" + str(sum))

cache = {}
russianPeasant(int(sys.argv[1]), int(sys.argv[2]), cache)
printResult(cache)

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Advertisement

Comments are closed.