karatsuba乘法
procedurekaratsuba(num1,num2) if(num1<10)or(num2<10) returnnum1*num2 /*calculatesthesizeofthenumbers*/ m=max(size(num1),size(num2)) m2=m/2 high1,low1=split_at(num1,m2) high2,low2=split_at(num2,m2) /*3callsmadetonumbersapproximatelyhalfthesize*/ z0=karatsuba(low1,low2) z1=karatsuba((low1+high1),(low2+high2)) z2=karatsuba(high1,high2) return(z2*10^(m))+((z1-z2-z0)*10^(m/2))+(z0)
#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; }
伪代码:
// 输入:n位长度的正整数x和y
// 输出:x*y的结果
函数 karatsuba (x, y) {
a和b为x的前半部分和后半部分;
c和d是y的前半部分和后半部分;
递归调用函数karatsuba解决q=a*c, 递归karatsuba解决p=b*d,递归karatsuba解决k=(a+b)(c+d)
返回10的n次方*q + 10的n/2次方 * (k - q - p) + p
}
https://zhuanlan.zhihu.com/p/144813558?from_voters_page=true