您的位置:首页 > 其它

分治法解决大整数乘法

2016-05-10 19:49 387 查看
#define SIGN(A) ((A > 0) ? 1 : -1)  

int IntegerMultiply(int X, int Y, int N)  

{  

    int sign = SIGN(X) * SIGN(Y);  

    int x = abs(X);  

    int y = abs(Y);  

    if((0 == x) || (0 == y))  

        return 0;  

    if (1 == N)  

        return x*y;  

    else  

    {  

        int XL = x / (int)pow(10., (int)N/2);   

        int XR = x - XL * (int)pow(10., N/2);  

        int YL = y / (int)pow(10., (int)N/2);  

        int YR = y - YL * (int)pow(10., N/2);  

          

        int XLYL = IntegerMultiply(XL, YL, N/2);  

        int XRYR = IntegerMultiply(XR, YR, N/2);  

        int XLYRXRYL = IntegerMultiply(XL - XR, YR - YL, N/2) + XLYL + XRYR;  

        return sign * (XLYL * (int)pow(10., N) + XLYRXRYL * (int)pow(10., N/2) + XRYR);  

    }  

}  

int _tmain(int argc, _TCHAR* argv[])  

{  

    int x = 1234;  

    int y = 4321;  

    cout<<"x * y = "<<IntegerMultiply(x, y, 4)<<endl;  

    cout<<"x * y = "<<x*y<<endl;  

    return 0;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息