大整数乘法的分治法实现

#include
#include
#include
#include
#include
#include
using namespace std;
#define SIGN(A) ((A > 0) ? 1 : -1)
typedef long long ll;
ll divide(ll X,ll Y,ll n)//X,Y位数相同时
{
int sign=SIGN(X)SIGN(Y);//求最终结果正负号,然后只进行正数运算即可
ll x=abs(X);
ll y=abs(Y);
if(x0||y0) return 0;
else if(n==1) return sign
xy;//分治算法递归的尽头
else
{
ll A=ll(x/pow(10,n/2));
ll B=ll(x-A
pow(10,n/2));
ll C=ll(y/pow(10,n/2));
ll D=ll(x-Cpow(10,n/2));
//把x,y按位数二分,分完之后每个元素都是位数相同的更小的数
ll AC=divide(A,C,n/2);//开始分治
ll BD=divide(B,D,n/2);//这里的AC BD都是乘对应的10的n次幂,都是单纯n/2的数
ll ABCD=divide((A-B),(D-C),n/2)+AC+BD//A-B,D-C的位数也是n/2;
return ll(AC
pow(10,n)+ABCD*pow(10,n/2)+BD);
}
}
//位数不同时候
long CalculateUnSame(long X, long Y, int xn, int yn)
{
if (X == 0 || Y == 0)
return 0;
else if ((xn == 1 && yn == 1) || xn == 1 || yn == 1)
return X * Y;
else
{
int xn0 = xn / 2, yn0 = yn / 2;
int xn1 = xn - xn0, yn1 = yn - yn0;

    long A = (long)(X / pow(10, xn0));
    long B = (long)(X % (long)pow(10, xn0));
    long C = (long)(Y / pow(10, yn0));
    long D = (long)(Y % (long)pow(10, yn0));

    long AC = CalculateUnSame(A, C, xn1, yn1);
    long BD = CalculateUnSame(B, D, xn0, yn0);
    long ABCD = CalculateUnSame((long)(A * pow(10, xn0) - B), (long)(D - C * pow(10, yn0)), xn1, yn1);

    return (long)(2 * AC * pow(10, (xn0 + yn0)) + ABCD + 2 * BD);
}

}
int main()
{

return 0;

}

你可能感兴趣的:(算法设计与分析上课)