Last active
July 15, 2020 19:09
-
-
Save diegocasmo/27988de71d4ab22f11654ce0fefff4b1 to your computer and use it in GitHub Desktop.
An implementation of Karatsuba multiplication algorithm in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Karatsuba | |
# Multiply two numbers using the Karatsuba | |
# multiplication algorithm | |
def multiply(num_1, num_2) | |
if num_1 < 10 || num_2 < 10 | |
return num_1 * num_2 | |
end | |
m_2 = [num_1.to_s.length, num_2.to_s.length].max/2 | |
# Split the digit sequences about the middle | |
high_1, low_1 = num_1.divmod(10**m_2) | |
high_2, low_2 = num_2.divmod(10**m_2) | |
# Recursively calculate the product using three | |
# multiplications of smaller numbers | |
z_0 = multiply(low_1, low_2) | |
z_1 = multiply((low_1 + high_1), (low_2 + high_2)) | |
z_2 = multiply(high_1, high_2) | |
return (z_2 * 10**(2 * m_2)) + ((z_1 - z_2 - z_0) * 10**(m_2)) + (z_0) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tests for this class can be found here: https://gist.github.com/diegocasmo/a6ea2f301e8efd5d2c08aefdb08dad41