Long Multiplication

Author

Eric W. Weisstein
April 30, 2006

This notebook downloaded from http://mathworld.wolfram.com/notebooks/Arithmetic/LongMultiplication.nb.

For more information, see Eric's MathWorld entry http://mathworld.wolfram.com/LongMultiplication.html.

©2006 Wolfram Research, Inc. except for portions noted otherwise

Additional Authors

Code by
George Beck
March 28, 2002

Code

RightJustify::usage = "RightJustify[x, w] gives a string of width w with the number x \
in the rightmost places.";

RightJustify[number_, width_] := 
	StringTake[
		StringJoin[
			Table[" ", {width}], 
			ToString @ number
		], 
	-width]

RightIndent::ussage = "RightIndent[x, {i}] gives the \
the number x as a string with i trailing blanks.";

RightIndent[number_, {indent_}] := 
	StringJoin[
		ToString @ number, 
		Table[" ", {indent - 1}]
	]

LongMultiply::usage="LongMultiply[x, y] shows the long multiplication of x by y. 
The numbers x and y must be non-negative integers.";

LongMultiply[x_, y_] := Module[
{X, Y, width},
{X, Y} = Map[IntegerDigits, {x, y}];
width = Length[Join @@ {X, Y}];
Print @ RightJustify[x, width];
Print @ RightJustify[y, width];
Print @ RightJustify[
	StringJoin @@ 
		Table["_", {1 + Max @ Map[Length, {X, Y}]}],
	width
];

Map[
	Print, 
	Map[RightJustify[#, width]&, 
		MapIndexed[
			RightIndent, 
			Map[
				RightJustify[#, width]&, 
				Reverse @ IntegerDigits[y] x 
			]
		]
	]
];

Print[StringJoin @@ Table["_", {width}]];
Print @ RightJustify[x y, width];
]

Examples

LongMultiply[123, 456]

LongMultiply[456, 123]

Wow! The same answer!

LongMultiply[123456789, 987654321]

Here's a way to look at how numbers are carried.

LongMultiply[9, 123456789]

Figures

({{ , 3, 8, 4}, {×,  , 5, 6}})

({{ ,  , 3, 8, 4}, {×,  ,  , 5, 6}, { , 2, 3, 0, 4}, {1, 9, 2, 0,  }, {2, 1, 5, 0, 4}})

({{ ,  ,  ,  ,  ,  , 6, 7, 4}, {×,  ,  , 2, 2, 0, 0, 0, 2}, { ,  ,  ,  ,  , 1, 3, 4, 8}, { , 1, 3, 4, 8, 0, 0, 0,  }, {1, 3, 4, 8,  ,  ,  ,  ,  }, {1, 4, 8, 2, 8, 1, 3, 4, 8}})

({{ ,  ,  ,  ,  ,  , 4(x^3), -, 3x, +, 6}, {×,  ,  ,  ,  ,  , 2(x^2), -, 4x, -, 3}, { ,  ,  , -, 12(x^3),  ,  , +, 9x, -, 18}, { , -, 16(x^4),  ,  , +, 12(x^2), -, 24x,  ,  }, {8(x^5),  ,  , -, 6(x^3), +, 12(x^2),  ,  ,  ,  }, {8(x^5), -, 16(x^4), -, 18(x^3), +, 24(x^2), -, 15x, -, 18}})