0
    """karatsuba algo"""
def fast(x,y):
    if len(str(x))==1 or len(str(y))==1:
        return x*y
    else:
        n = max(len(str(x)),len(str(y)))
        m = n//2

        a = x//10**m
        b = x%10**m
        c = y//10**m
        d = y%10**m

        k = fast(a,c)
        n = fast((a+b),(c+d))
        o = fast(b,d)

        return (10**2*m*k) +(10**m*(n-k-o))+(o)
print(fast(10515610,5651551460))

python shouldn't have any overflow problem. Then why it's returning minus answer when the input is big ?

  • That's not the case. If you try `print(fast(1051599610,5651460))` you will get `441780299400` So it's the operations that caused it. – Red Jun 11 '20 at 02:05
  • The only source of negative numbers, for positive inputs, is `n-k-o`. So if you're seeing a negative result, one would assume that `n < k+o` at some point. – Tom Karzes Jun 11 '20 at 02:05
  • `10**2*m*k` is misparenthesized. – user2357112 Jun 11 '20 at 02:17

2 Answers2

0

Looking at the original algorithm, your code should be

return (10**(2*m)*k) +(10**m*(n-k-o))+(o)

Look at the additional parenthesis around (2*m). Otherwise you're multiplying by m instead of raising to the power.

You could probably make it all more readable and efficient by replacing all the 10**m bits with a new variable

JBernardo
  • 32,262
  • 10
  • 90
  • 115
-1

I checked this and found that problem is not in Python overflow. Your value of o in last iteration is way to large in comparison to k or n. Both k and n got the value 6 while o contains 17487400. So n-k-o caused negative result.

EduardoSaverin
  • 545
  • 4
  • 19