#Programming Assignment #1
#what's the product of the following two 64-digit numbers?
#Using karatsuba multiplication algorithm
def Karatsuba(x,y):
if (len(str(x))) < 2 or (len(str(y))) < 2:
return x*y
else:
#m这里不确定是否可以任意设置(实际上可以是任意正整数,对于长整数,为了便于计算,通常设置为较长整数宽度的一半)
m=max(len(str(x)),len(str(y)))//2
x1=x//int(pow(10,m))
x0=x-x1*int(pow(10,m))
y1 =y//int(pow(10, m))
y0=y-y1*int(pow(10,m))
z2 = Karatsuba(x1,y1)
z0 = Karatsuba(x0,y0)
z1 = Karatsuba((x1 + x0), (y1 + y0)) - z2 - z0
return z2 * pow(10,2*m) + z1 * pow(10,m) + z0
result=Karatsuba(num1,num2)
Karatsuba算法(Python)
最新推荐文章于 2024-09-17 08:00:00 发布