0

我已经在 C++ 中实现了 karatsuba 乘法算法。我想对其进行优化,以便可以将两个 64 位数字相乘。有人可以帮忙吗?谢谢 :)

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;
    }
}
4

0 回答 0