乘法——Karatsuba乘法

#include <stdio.h>
#include <math.h>

//找到x的位数
int size(long x){
	int count=0;
	do{
		count++;
		x=x/10;
	}while(x);
	return count;
}

//找到x和y的最大值
int max(int x, int y){
	return x>y?x:y;
}

int getHigh(int x, int m){
	return x / (int)pow(10,m);
}

int getLow(int x,int m){
	return x - getHigh(x,m)*(int)pow(10,m); 
}

//大数相乘算法:比如1234,5678
//拆分为12,34   56,78
//x=x1*10^m+x0
//y=y1*10^m+y0
//满足:m<n且x0,y0<10^m
//
long karatsuba(long x, long y){
	int m;
	int x1,x0;
	int y1,y0;

	int z0;
	int z1;
	int z2;

	//结束递归
	if(x<10||y<10)
		return x*y;
	
	//获得拆分的位数
	//printf("%d\n",max(size(x),size(y)));
	m = max(size(x),size(y)) / 2;
	printf("%d\n",m);

	x0 = getLow(x,m);
	x1 = getHigh(x,m);
	y0 = getLow(y,m);
	y1 = getHigh(y,m);

	printf("分拆%d==%d\n",x,y);	
	printf("分拆x0===%d\n",x0);	
	printf("分拆x1===%d\n",x1);
	printf("分拆y0===%d\n",y0);
	printf("分拆y1===%d\n",y1);
	
	z2 = karatsuba(x1,y1);
	printf("z2===%d\n",z2);
	z0 = karatsuba(x0,y0);
	printf("z0===%d\n",z0);
	z1 = karatsuba((x1+x0),(y1+y0)) - z2 - z0;
	printf("z1===%d\n",z1);
	//return 0;
	return z2*(int)pow(10,2*m)+z1*(int)pow(10,m)+z0;
}

void main(){
	printf("%ld\n",karatsuba(1234,56789));
	return;
}

    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/maoxunxing/article/details/41308247
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞