Search code examples
c++implementationkaratsuba

Karatsuba Implementation C++


So I've decided to take a stab at implementing Karatsuba's algorithm in C++ (haven't used this language since my second coding class a life time ago so I'm very very rusty). Well anyhow, I believe that I've followed the pseudocode line by line but my algorithm still keeps popping up with the wrong answer.


    x = 1234, y = 5678
    Actual Answer: x*y ==> 7006652
    Program output: x*y ==> 12272852

*Note: I'm running on a mac and using the following to create the executable to run c++ -std=c++11 -stdlib=libc++ karatsuba.cpp

Anywho, here's the code drafted up and feel free to make some callouts on what I'm doing wrong or how to improve upon c++.

Thanks!

Code:

    #include <iostream>
    #include <tuple>
    #include <cmath>
    #include <math.h>
    
    using namespace std;
    
    /** Method signatures **/
    tuple<int, int> splitHalves(int x);
    int karatsuba(int x, int y, int n);
    
    int main()
    {
        int x = 5678;
        int y = 1234;
        int xy = karatsuba(x, y, 4);
        cout << xy << endl;
        return 0;
    }
    
    int karatsuba(int x, int y, int n)
    {
        if (n == 1)
        {
            return x * y;
        }
        else
        {
            int a, b, c, d;
            tie(a, b) = splitHalves(x);
            tie(c, d) = splitHalves(y);
            int p = a + b;
            int q = b + c;
            int ac = karatsuba(a, c, round(n / 2));
            int bd = karatsuba(b, d, round(n / 2));
            int pq = karatsuba(p, q, round(n / 2));
            int acbd = pq - bd - ac;
            return pow(10, n) * ac + pow(10, round(n / 2)) * acbd + bd;
        }
    }
    
    
    /** 
     * Method taken from https://stackoverflow.com/questions/32016815/split-integer-into-two-separate-integers#answer-32017073
     */
    tuple<int, int> splitHalves(int x)
    {
        const unsigned int Base = 10;
        unsigned int divisor = Base;
        while (x / divisor > divisor)
            divisor *= Base;
        return make_tuple(round(x / divisor), x % divisor);
    }

Solution

  • There are a lot of problems in your code...

    First, you have a wrong coefficient here:

                int q = b + c;
    

    Has to be:

                int q = c + d;
    

    Next, the implementation of splitHalves doesn't do the work. Try that:

    tuple<int, int> splitHalves(int x, int power)
    {
            int divisor = pow(10, power);
            return make_tuple(x / divisor, x % divisor);
    }
    

    That would give you the "correct" answer for your input, but... that is not a Karatsuba method.

    First, keep in mind that you don't need to "split in halves". Consider 12 * 3456. splitting the first number to halves mean a = 0, b = 12, while your implementation gives a = 1, b = 2.

    Overall Karastuba works with arrays, not integers.