0

I have implemented karatsuba multiplication algorithm in C++. I want to optimize it so that I can multiply two 64 digits numbers. Can someone help, please? Thank you :)

int Karatsuba::count(long long int a)
{
    ostringstream str1; 
    str1 << a; 
    string s = str1.str(); 
    return s.length();
}
long long int Karatsuba::multiply(long long int x, long long int y)
{
    if(x / 10 == 0 || y / 10 == 0)
        return x*y;
    else
    {
        int n = count(x);
        long long int n2 = (long)pow(10, n/2);
        
        long long int a = x / n2;
        long long int b = x % n2;
        long long int c = y / n2;
        long long int d = y % n2;
        
        long long int ac = multiply(a,c);
        long long int bd = multiply(b,d);
        long long int step3 = multiply((a+b), (c+d));
        
        return (pow(10, n)*ac) + (n2*(step3 - ac - bd)) + bd;
    }
}
tadman
  • 208,517
  • 23
  • 234
  • 262
Ayushi
  • 1
  • 1
    If you want to optimize it you'll want to avoid converting to a string and counting digits that way. – tadman Jun 21 '20 at 07:32
  • Tip: Instead of `long long int` you might want to pin that down and use a [shorter identifier as well](https://en.cppreference.com/w/cpp/types/integer), like `uint64_t`. – tadman Jun 21 '20 at 07:33
  • The function returns a `long long int`. If the result actually fits in a `long long int`, then all you need to do is `return x * y;` – user3386109 Jun 21 '20 at 07:35

0 Answers0