我正在尝试实现python 2.7中的课程中提到的Karatsuba算法。这是我目前的代码:
# Karatsuba multiplication implementation in python
import numpy as np
import sys
# x = 10^(n/2)*a + b and y = 10^(n/2)*c + d
# x.y = 10^n*(ac) + 10^(n/2)*(ad + bc) + bd
# now recursively compute ac, ad, bc and bd
sys.setrecursionlimit(15000)
def algo_recurs(val1, val2):
# Assuming that the length of both the multiplier and multiplicand is
same
# Currently employing numbers which are of length 2^n
n = len(str(val1)) # n = 4
print(n)
divVal = 10**(n/2)
a = val1 / divVal # a = 12
b = val1 % divVal # b = 34
c = val2 / divVal # c = 43
d = val2 % divVal # d = 21
# let the example case be 1234 * 4321
if(len(str(val1)) == 2):
prob1 = a * c
prob2 = b * d
prob3 = (a+b)*(c+d) - prob1 - prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
return(finalResult)
else:
prob1 = algo_recurs(a,c)
prob2 = algo_recurs(b,d)
prob3 = algo_recurs((a+b),(c+d)) - prob1 -prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
#print(finalResult)
return(finalResult)
#Enter the inputs
multiplicand = input("Enter the multiplicand:")
multiplier = input("Enter the multiplier:")
output = algo_recurs(multiplicand, multiplier)
print(output)
上面的代码适用于长度为4或更短的数字。但是当我超越它时,它会引发以下错误:
File "Karatsuba.py", line 31, in algo_recurs
prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 31, in algo_recurs
prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 31, in algo_recurs
prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 15, in algo_recurs
n = len(str(val1)) # n = 4
RuntimeError: maximum recursion depth exceeded while getting the str of an object
我也增加了递归限制,认为它可能是问题。但这也没有解决它。
如果你能指出我在实施中可能做错了什么,我将不胜感激。
无论您设置递归限制有多高,您的算法都不会终止。这是因为一旦val1
达到单个数字,参数a和c将始终保持不变,因为那时n
为1而10**(n/2)
也为1。
更改递归限制是危险的,因为通常当您超过递归限制时,这是因为您的程序包含错误或设计决策不佳。递归总是可以用相等或更低内存成本的迭代替换。
除非你的算法坚持你这样做,因为知道在某些时候你会收到一个结果,你可以在每次调用函数时改变最大递归深度,但我再也不建议你因为你的程序超过1500次递归调用对此而言,这是相当过分的。
# Karatsuba multiplication implementation in python
import numpy as np
import sys
def algo_recurs(val1, val2):
sys.setrecursionlimit(sys.getrecursionlimit() + 1) # Changes the recursion limit every time
n = len(str(val1))
#print(n)
divVal = 10**(n/2)
a = val1 / divVal # a = 12
b = val1 % divVal # b = 34
c = val2 / divVal # c = 43
d = val2 % divVal # d = 21
if(len(str(val1)) == 2):
prob1 = a * c
prob2 = b * d
prob3 = (a+b)*(c+d) - prob1 - prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
return(finalResult)
else:
prob1 = algo_recurs(a,c)
prob2 = algo_recurs(b,d)
prob3 = algo_recurs((a+b),(c+d)) - prob1 -prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
return(finalResult)
multiplicand = int(input("Enter the multiplicand:"))
multiplier = int(input("Enter the multiplier:"))
output = algo_recurs(multiplicand, multiplier)
print(output)