I just got to know about Karatsuba Algorithm, and I tried to implement it in Haskell.
Here is my code:
(***) :: Integer -> Integer -> Integer
x *** y
| max x y < ub = x*y
| otherwise =z2*base*base + ((x1+x0)***(y1+y0)-z2-z0)*base + z0
where
base =10^((length . show $ max x y) `div` 2)
z2 =x1***y1
z0 = x0***y0
(x1, x0) = helper x
(y1, y0) = helper y
helper n = (n `div` base, n `mod` base)
ub = 10000
This works accurately as long as I checked with large numbers like 20 -30 digits and fast enough for 10-20 digits. However, this is a a lot slower than normal *
when 100 digits or even bigger numbers. How I can improve this algorithm?
base =10^((length . show $ max x y)
div` 2)` is not good. Although GHC'sShow
instance forInteger
is orders of magnitude faster than Java'sBigInteger.toString()
or Python'sstr
for large numbers, that is still fairly slow (think about what it has to do). You should get a nice speedup usingGHC.Float.integerLogBase
there. Still better if you used a power-of-2 base, probably. – Daniel Fischer Jun 8 '13 at 5:12