我试图在Ruby中实现Karatsuba乘法。
# takes two integer x and y and partition them to x=a+b and y=c+d
# example if x = 1234 a=12 and b=34
# recursively compute a*c,a*d,b*c and b*d
def mult (x,y)
if len(x) == 1 && len(y) == 1
return x*y
elsif len(x) > 1 && len(y) > 1
ab = partition(x)
cd = partition(y)
return ab.product(cd).each{ |num| mult(num[0],num[1]) }
end
end
#method for partitioning works fine..
def partition(number)
number.divmod( 10**(len(number)/2) )
end
#method to find size of integer works fine...
def len(value)
value.to_s.split("").compact.size
end
所以
的预期回报 p mult(12,34) should be 3,4,6,8
but is [[1, 3], [1, 4], [2, 3], [2, 4]]
而不是return x*y
,当我在print "#{x*y}"
中使用line no:3
时,它会打印3,4,6,8。我无法理解mult
方法为nil
返回x*y
的原因。
答案 0 :(得分:4)
问题是错误的迭代器:
# ⇓⇓⇓⇓
ab.product(cd).each{ |num| mult(num[0],num[1]) }
你想要的是Enumerable#map
而不是:
ab.product(cd).map { |num| mult(num[0], num[1]) }
旁注:您也无需明确调用return
:
def mult (x,y)
if len(x) == 1 && len(y) == 1
x*y
elsif len(x) > 1 && len(y) > 1
ab = partition(x)
cd = partition(y)
ab.product(cd).map { |num| mult(num[0], num[1]) }
else
raise "We got a problem"
end
end
#method for partitioning works fine..
def partition(number)
number.divmod( 10**(len(number)/2) )
end
#method to find size of integer works fine...
def len(value)
value.to_s.size
end
p mult 12, 34
#⇒ [3,4,6,8]