python - 如何改进我的 karatsuba Logic 以使我的代码正常工作?
问题描述
无法让我的 Karatsuba 算法正常工作。我的代码中有一个无限循环。我认为问题开始于:
q = str(int(c) + int(d))
因为 None 是返回值。为什么没有返回?
到目前为止,我的调查使我得出结论,我的无限循环是:
pq = Karatsuba(p, q)
重新调整我的代码,但到目前为止没有任何效果。
def Karatsuba( x, y):
'''
Input: Two n-digit positive integers. N must be a power of two.
Output: The product of x and y.
'''
if len(x) == 1 and len(y) == 1:
return int(x) * int(y)
else:
split = len(x) // 2
a = x[:split]
b = x[split:]
c = y[:split]
d = y[split:]
ac = Karatsuba(a, c)
bd = Karatsuba(b, d)
p = str(int(a) + int(b))
q = str(int(c) + int(d))
pq = Karatsuba(p, q)
adbc = pq - ac - bd
return 10**len(x) * ac + (10**split) * adbc + bd
print(Karatsuba('1234', '5678'))
产生的答案应该是 7006652
解决方案
推荐阅读
- html - 如何在 li 元素中设计一个列表 css div?
- asp.net-core - 在 Google Cloud Run 上托管的 ASP.NET Core 应用程序中频繁注销
- javascript - 出现登录表单消失登录按钮,反之亦然
- opengl - 在 3D 上渲染 2D 之前使用正射投影
- javascript - 基于 React App 中的 repo 语言的 Github 语言颜色
- html - 动态表单字段不进入行
- regex - 无法使用正则表达式获取匹配数组
- c++ - 访问冲突读取位置 0xCDCDCDCD 与类
- python - get() 接受 2 到 3 个位置参数,但给出了 4 个
- r - 如何在 doubleYScale 上编辑 ylab2?