Wednesday, May 20, 2015

5/20/15 - Peasant Multiplication

Today in math, we learned about a method of multiplication called Peasant Multiplication that works for positive whole numbers, and is pretty cool. Here's a rundown on how it works, although it's kind of hard to understand and I'm not sure how well the website explains it.

I implemented this in ruby!
def multiply(number1, number2)
# convert number1 to binary and reverse it
# so that the most significant bit is last
n1_binary_str = number1.to_s(2).reverse
binary_array = n1_binary_str.split '' # convert string to array
add_amount = nil
total = 0
binary_array.each_with_index do |char, index|
# double the add_amount, or set it to number2 if it is nil
add_amount = add_amount ? (add_amount + add_amount) : number2
# add add_amount to the total if the binary for
# number2 has a binary 1 in given place
total += add_amount if char == '1'
end
return total
end
multiply 1, 2
#=> 2
multiply 400, 2
#=> 800
multiply 400, 20
#=> 8000
multiply 400, 200
#=> 80000

View it in action here by pressing the run button

The full code I wrote is here, which is extensible in case I get around to testing the efficiency of this algorithm compared to other methods.

No comments:

Post a Comment