vjb vjb - 1 year ago 57
C++ Question

Karatsuba C++ Implementation

I'm having some trouble implementing the Karatsuba algorithm. My project limits me to the following libraries: iostream, iomanip, cctype, cstring. Also, I'm limited to only using the integer built-in type and arrays/dynamic arrays to handle numbers (only unsigned integers will be input). I've built a class to handle integers of arbitrary size using dynamic arrays. I need to implement a function that multiplies big integers, and I'd like to use Karatsuba if possible. The trouble I'm running into is how to break apart large integers and do the multiplications called for in the algorithm. I assume this should be done recursively. I was hoping someone could give me an example of how to do this.

For example:

I have two numbers stored in dynamic arrays. Let's say they are:

X = 123456789123456789123456789
Y = 987654321987654321987654321987654321

How would Karatsuba need to handle this, given the storage limitations on the unsigned int type? Any help would be much appreciated!

Answer Source

If you look at the Pseudo-code here, you can modify it a little to use with an array like so:

procedure karatsuba(num1, num2)

    if (num1.Length < 2) or (num2.Length < 2) //Length < 2 means number < 10    
        return num1 * num2 //Might require another mult routine that multiplies the arrays by single digits

    /* calculates the size of the numbers */
    m = max(ceiling(num1.Length / 2), ceiling(num2.Length / 2))
    low1, low2 = lower half of num1, num2
    high1, high2 = higher half of num1, num2

    /* 3 calls made to numbers approximately half the size */
    z0 = karatsuba(low1,low2)
    z1 = karatsuba((low1+high1),(low2+high2))
    z2 = karatsuba(high1,high2)

    //Note: In general x * 10 ^ y in this case is simply a left-shift
    //      of the digits in the 'x' array y-places. i.e. 4 * 10 ^ 3
    //      results in the array x[4] = { 4, 0, 0, 0 }
    return (z2.shiftLeft(m)) + ((z1-z2-z0).shiftLeft(m/2)) + (z0)

Provided you have an addition, subtraction and extra single-digit multiplication routine defined for your number arrays this algorithm should be implemented pretty easily (of course along with the other required routines such as digit shifting and array splitting).

So, there is other preliminary work for those other routines, but that is how the Karatsuba routine would be implemented.