我花了一段时间用Python实现Karatsuba的算法,但是当我试图将两个较大的数字(超过10^15)相乘时,我的结果开始变得不准确。我搞不懂为什么。
附带问题:我的基本情况是否有一种方法:“(而不是两者之一)x和y都严格地小于10”。
def karatsuba(x, y):
# 1. Split ints
if x <= 10 or y <= 10:
#Base case
return x * y
n_x = ceil(log(x, 10)) # Nb of digits in x
n_y = ceil(log(y, 10))
n = max(n_x, n_y)
b = int(x % (10 ** (n // 2)))
a = int(x / (10 ** (n // 2)))
d = int(y % (10 ** (n // 2)))
c = int(y / (10 ** (n // 2)))
# 2. Recursive calls
ac = karatsuba(a, c)
bd = karatsuba(b, d)
kara = karatsuba((a + b), (c + d))
res = ac * (10 ** (2*(n//2))) + (kara - ac - bd) * (10 ** (n//2)) + bd
return res例子:
x = 151222321858446622145369417738339374
y = 875336699541236667457869597252254524
karatsuba(x, y)返回:
132370448112535269852891372864998437604548273605778561898354233338827976而不是:
132370448112535277024334963430875927265604725663292579898354233338827976发布于 2022-02-05 01:13:15
由于您的float部门,您通过/就失去了精度。使用//代替。然后,您也不需要转换回int。更好的是,使用divmod
N = 10 ** (n // 2)
a, b = divmod(x, N)
c, d = divmod(y, N)https://stackoverflow.com/questions/70994440
复制相似问题