Welcome, guest | Sign In | My Account | Store | Cart

Here is a very simple program in Python to multiply 2 numbers. This version follows the Russian Multiplication Algorithm. I worte for my blog Captain DeadBones Chronicles

Python, 29 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sys

def main(argv):

	if len(argv) != 2:
		sys.exit('Usage: russian_multi.py <a> <b>')
		
	a = int(sys.argv[1])
	b = int(sys.argv[2])
	
	sum = 0;

	if a == 0 or b == 0:
		print 0;
		exit();

	if b%2 == 1:
		sum += a;

	while b != 1:
		a = a*2;
		b = b/2;
		if b%2 == 1:
			sum += a;
		
	print "The result of " + str(a) + " times " + str(b) + " is: " + str(sum)

if __name__ == "__main__":
	main(sys.argv[1:])