0

Karachuba algorithm : https://en.wikipedia.org/wiki/Karatsuba_algorithm

threshold = 4


def prod2(a, b):
    n = max(len(str(a)), len(str(b)))
    if a == 0 or b == 0:
        return
    elif n <= threshold:
        return a*b

    else:
        m = n/2
        x = a/pow(10, m)
        y = a % pow(10, m)
        w = b/pow(10, m)
        z = b % pow(10, m)
        r = prod2(x+y, w+x)
        p = prod2(x, w)
        q = prod2(y, z)
        return p*pow(10, 2*m) + (r-p-q)*pow(10, m)+q


a = 12314124
b = 123123
print(prod2(a, b))

RecursionError: maximum recursion depth exceeded while getting the str of an object

I have implemented the Karachuba algorithm in Python and return it appropriately depending on the input value, but I don't know why the recurtion error occurs.

2
  • 1
    you are returning null Commented Oct 31, 2021 at 1:48
  • 1
    The / in x = a/pow(10, m) is performing floating division. You need to use the // integer division operator, there and elsewhere. That's probably not your only bug Commented Oct 31, 2021 at 1:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.