# Ruby Multiplies Like a Fourth Grader

Join the DZone community and get the full member experience.

Join For Free

*
ruby
multiplies large integers using the same algorithm we learned in
elementary school.
*

imagine yourself as an 8 or 9 year old at a chalkboard learning to multiply. your teacher asks you to write one number over another, and then to draw an “x” and a line below. next you multiply the numbers one digit at a time, using the multiplication table you memorized the year before. your teacher also shows you how to “carry” values from one column to the next when they don’t fit as a single digit.

after studying ruby’s multiplication algorithm, i was surprised to find out that ruby multiplies large numbers (bignum’s) the same way you learned in fourth grade: one “digit” at a time. my post today will give you a quick refresher course on fourth grade math, and then explain how ruby’s bignum class uses the same classic, long multiplication algorithm you learned in elementary school!

## a crash course in fourth grade math

we all remember multiplication tables: memorizing them was either a fun mental exercise – or a painful form of torture – depending on our mathematical aptitude and the personality of our grade school teacher. regardless, there were two reasons for memorizing simple products such as 5 x 6 = 30 or 9 x 7 = 63. first, these simple problems occur frequently; and second, they help us later when multiplying larger numbers.

maybe you flunked out of school before the fourth grade, or more likely you’ve become so dependent on your iphone’s calculator app you don’t remember how to multiply by hand. before we look at how ruby multiplies numbers, let’s review the classic long multiplication algorithm.

here’s a sample problem:

now walk up to the chalkboard and write the two numbers one above the other, the larger number on top:

remember what to do next? for me fourth grade was in the 1970s, but somehow it still comes back to me! start by multiplying the rightmost digits from each number together (2 x 9 = 18), placing the product below the line:

however, since 18 is too large to fit into a single digit you “carry” the 1 up to the top of the next column, and leave the 8 behind:

next multiply 9 again by the next digit from the top number, 3 in this example, adding the 1 you carried from the last step. so you calculate (9x3)+1 = 28.

here i’ve written the 28 below the line, to the left of the previous 8 value. so far you’ve calculated that 9x32 = 288.

remember what to do next? i know it’s been a long time! repeat the process with the next digit from the lower number, 2. in other words, you calculate 2x32=64. however, this time you write the product farther below, shifted to the left like this:

you shift the numbers to the left because the 2 from 29 is actually a 20. now all you need to do is add the two intermediate products together, like this:

drop the first 8 down, add 8+4=12, carry the 1 and finally calculate 1+2+6 = 9. you have the answer, 928. congratulations, you’ve managed to multiply two numbers by hand without a calculator!

## ruby’s multiplication table

*the intel 4004 was the first*

commercially available microprocessor

(source: wikimedia commons )

commercially available microprocessor

(source: wikimedia commons )

to multiply small numbers ruby doesn’t implement a software algorithm. instead, ruby relies on your computer’s microprocessor’s hardware circuits to perform the calculation. your microprocessor, in a sense, plays the role of a multiplication table for ruby. by using a machine language instruction to multiply numbers, ruby can get simple products very quickly. this is loosely analogous to you or i memorizing the simple products from the multiplication table in our heads.

as i discussed in my last article , ruby stores small integers as native 64-bit values using the fixnum class. for example, in ruby we could multiply two numbers like this:

when you execute this program, ruby’s internal c code represents these two numbers as fixnum objects:

as you can see, ruby represents each fixnum with a 64-bit binary value with the least significant bit (fixnum_flag) set. when it needs to multiply, ruby first removes the fixnum_flag bit and is left with the actual binary values 5 and 6. now it can perform the multiplication using a native machine language instruction.

above imulq is the intel x86-64 assembly language instruction for multiplying integers. ruby relies on the microprocessor to calculate 5x6 and to return the product 30, shown as binary at the bottom.

## a fourth grader that knows hexadecimal

ruby multiplies large numbers exactly the same way you and i do, using the classic long multiplication algorithm. we use long multiplication to multiply numbers larger than 12, since the multiplication tables we memorized went up to 12. ruby uses long multiplication for numbers that don’t fit into a fixnum object – numbers so large that a single machine language instruction can’t process them.

here’s an example problem:

the number 29 fits into a fixnum no problem, but 10000000000000000000 does not. instead, ruby represents this large integer using a bignum object, like this:

you can see a simplified view of the rbignum c structure at the top. the digits pointer saves the location of an array of 32-bit values, the “digits.” as i explained in my last article , the digits are actually out of order, with the lower 32 bits on the left and the top 32 bits on the right.

since ruby represents bignum’s with a complex data structure and not simple 64-bit integers, it can’t use machine language instructions to perform mathematical operations on them. what does ruby do instead? how did it calculate 10000000000000000000 * 29 above?

it turns out ruby uses long multiplication, just as we did in fourth grade! the only difference is that ruby uses 32-bit “digits,” instead of digits that contain decimal values from 0-9.

to see what i mean, here’s another look at the 32x29 problem we did earlier:

above i show a rectangle around each 0-9 decimal digit. remember the long multiplication algorithm works on one pair of digits at a time. the 0-9 notation means that each digit can hold a value between 0 and 9.

now let’s take another look at the large integer multiplication ruby executed above:

if i redraw this using 32-bit “digits,” i get this:

each rectangle is a 32-bit word present in a bignum digit data structure. at the bottom we see 0x1d, which is 29. (this does fit into a fixnum but ruby moves it to a bignum before the multiplication starts.) above that are the bits from the rbignum structure, shown in the proper order. 0x8ac72304 are the most significant 32 bits and 0x89e80000 are the least significant 32 bits. in order words, the hexadecimal value 0x8ac7230489e80000 is equivalent to 10000000000000000000.

it might seem bizarre to show a multiplication problem this way, but remember ruby is a very special fourth grader, one that knows how to perform binary math and can understand hexadecimal.

## multiplying bignums using long multiplication

once we’ve drawn the problem using 32-bit hexadecimal digits, we’ll be able to see that ruby performs long multiplication just like you or i did back in school. first, it multiplies the rightmost digits from each number.

so we have 0x89e80000 * 0x1d = 0xf9f480000. but now the top 4 bits, the 0xf, doesn’t fit into a single 32-bit value. so ruby “carries” the 0xf to the next column.

you can see above the carried value 0xf at the top left, and the remaining bits in the 32-bit digit at the bottom right.

now ruby calculates 0x8ac72304 * 0x1d + 0xf and gets 0xfb88ef783.

once again, 0xfb88ef783 doesn’t fit into 32 bits, so ruby carries the extra 0xf to the next column. since this was the last column, ruby is done and just moves the extra 0xf into a new 32-bit digit:

and now we have our answer:

## multiplication of extremely large numbers

this was a very simple example, because 29 was actually a small integer. this meant ruby didn’t need to use multiple rows in the long multiplication process, adding them together to get the final result. but ruby would use multiple rows in long multiplication just the way we would if both numbers were large.

however, ruby’s bignum class was also designed to handle extremely large numbers that might contain thousands of digits. you might need these for certain scientific applications or in cryptography, for example. to handle extremely large numbers, the bignum class also contains some alternative, advanced mathematical algorithms for multiplication, division and more. ruby 2.1 also now optionally supports the gmp, the gnu multiple precision arithmetic library . in my next post i’ll take a look at how to enable gmp support and how to use it.

Published at DZone with permission of Pat Shaughnessy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Comments