Search code examples
algorithmrecursionkaratsuba

Base case for Karatsuba Multiplication


Just wondering why the base case for Karatsuba multiplication ( shown here: http://www.sanfoundry.com/java-program-karatsuba-multiplication-algorithm/) is chosen to be "N<= 10"? I found "N<= 4, 3, 2 ,1 " will not give me a correct result. Anyone can explain?


Solution

  • Karatsuba's algorithm will work correctly with any "sufficiently large" base case, where "sufficiently large" means "large enough that when it's divided into smaller subproblems, those subproblems are indeed smaller and produce the right answer." In that sense, there isn't "a" base case for Karatsuba as much as a general rule for what base cases might look like.

    Honestly, the code you linked doesn't seem like it's a very reasonable implementation of the algorithm. It works with longs, which can already be multiplied in O(1) time on any reasonable system, and their base case is to stop when the numbers are less than 1010, meaning that with 64-bit numbers the recursion always terminates after a single step. A better implementation would likely use something like a BigInteger type that can support arbitrary-precision multiplication. At that point, choosing the optimal base case is a matter of performance tuning. Make the base case have a number of digits that's too small and the recursion to handle smaller numbers will take dramatically more time than just doing a naive multiply. Make the base too high and you'll start to see slowdown as cases better handled by the recursive step instead get spend using naive multiplications.