Karasuba算法,略有误差

tim*_*_76 1 python algorithm karatsuba

我花了一段时间尝试在 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

Run Code Online (Sandbox Code Playgroud)

例子 :

x = 151222321858446622145369417738339374
y = 875336699541236667457869597252254524
karatsuba(x, y)
Run Code Online (Sandbox Code Playgroud)

返回:

132370448112535269852891372864998437604548273605778561898354233338827976
Run Code Online (Sandbox Code Playgroud)

代替:

132370448112535277024334963430875927265604725663292579898354233338827976
Run Code Online (Sandbox Code Playgroud)

Kel*_*ndy 6

float由于你的划分,你会失去精确度///代替使用。那么您也不需要转换回int. 更好的是,使用divmod

    N = 10 ** (n // 2)
    a, b = divmod(x, N)
    c, d = divmod(y, N)
Run Code Online (Sandbox Code Playgroud)