Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Last active July 15, 2020 19:09
Show Gist options
  • Save diegocasmo/27988de71d4ab22f11654ce0fefff4b1 to your computer and use it in GitHub Desktop.
Save diegocasmo/27988de71d4ab22f11654ce0fefff4b1 to your computer and use it in GitHub Desktop.
An implementation of Karatsuba multiplication algorithm in Ruby
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
@diegocasmo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment