0

I'm not getting what is wrong in my code. How should I fix this recursion error in Karatsuba multiplication?

def karatsuba(x,y):
    if len(str(x))==1 or len(str(y))==1:
        return int(x)*int(y)
    else:
        n=max(len(str(x)),len(str(y)))
        nby2=n//2
        a=x/(10**nby2)
        b=x%(10**nby2)
        c=y/(10**nby2)
        d=y%(10**nby2)
        ac=karatsuba(a,c)
        bd=karatsuba(b,d)
        k=karatsuba(a+b,c+d)-ac-bd
        p=((10**2*nby2)*ac+((10**(nby2))*k)+bd)
        return p

Error messages-

line 11, in karatsuba
    ac=karatsuba(a,c)
  [Previous line repeated 989 more times]

 line 2, in karatsuba
    if len(str(x))==1 or len(str(y))==1:
RecursionError: maximum recursion depth exceeded while getting the str of an object
gilch
  • 10,813
  • 1
  • 23
  • 28
Muskan Kalra
  • 53
  • 1
  • 8
  • 1
    A first comment unrelated to the error: when is `len(str(x))==1`? When `x<10`... And why take `int(x)` if `x` is an integer? –  Aug 19 '19 at 06:13
  • 1
    Add a `print(x,y)` as the first statement of your function and you will see the issue. – Selcuk Aug 19 '19 at 06:16
  • Note also that `10**2*nby2` is not `10**(2*nby2)` but `(10**2)*nby2`. And given that you write `//` for one of the divisions, I expect `x/(10**nby2)` to be a float. –  Aug 19 '19 at 06:18

1 Answers1

0

x/(10**nby2) returns float so it has to be x//(10**nby2). Also change (10**2*nby2) to (10**(2*nby2)

def karatsuba(x,y):
    if len(str(x))==1 or len(str(y))==1:
        return int(x)*int(y)
    else:
        n=max(len(str(x)),len(str(y)))
        nby2=n//2
        a=x//(10**nby2)
        b=x%(10**nby2)
        c=y//(10**nby2)
        d=y%(10**nby2)
        ac=karatsuba(a,c)
        bd=karatsuba(b,d)
        k=karatsuba(a+b,c+d)-ac-bd
        p=((10**(2*nby2))*ac+((10**(nby2))*k)+bd)
        return p
wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29