Created
October 16, 2014 13:35
-
-
Save sduquej/85a40572b8c331997841 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Multiplies two n-length integers using recursively the Karatsuba altorithm | |
class Karatsuba | |
def initialize | |
end | |
def self.karatsuba(x, y) | |
return x * y if (x < 10) || (y < 10) | |
n = [x.to_s.size, y.to_s.size].max | |
n2 = n/2 | |
# Initial values | |
a, b = x.divmod(10**n2) | |
c, d = y.divmod(10**n2) | |
# Terms used on the algorithm computation | |
t1 = karatsuba a, c | |
t2 = karatsuba b, d | |
t3 = karatsuba((a+b), (c+d)) - t1 - t2 | |
(t1*10**(2*n2))+(t3*10**n2)+(t2) | |
end | |
end | |
puts 'We will multiply two numbers karatsuba-way' | |
puts 'What is the first number?' | |
x = gets.to_i | |
puts 'What is the second number?' | |
y = gets.to_i | |
product = Karatsuba.karatsuba(x, y) | |
puts "#{x} . #{y} = #{product}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment