0

my code below seem to work well if either number's length is even, but if both length of number are odd(like in the pic), it outputs the wrong result. I have no idea where it went wrong or how to fix it.

def karatsubaMulti(num1, num2):
    len1 = len(str(num1))
    len2 = len(str(num2))

    if len1==1 or len2==1:
        return num1*num2

    else:
        maxLen = max(len1, len2)

        if maxLen > len1:
            a=0
            b=num1
        else:
            a = num1 // pow(10, maxLen//2)
            b = num1 %  pow(10, maxLen//2)

        if maxLen > len2:
            c=0
            d=num2
        else:
            c = num2 // pow(10, maxLen//2)
            d = num2 % pow(10, maxLen//2)
        z1 = karatsubaMulti(a, c)
        z2 = karatsubaMulti(b, d)
        z3 = karatsubaMulti(a+b, c+d)
        return z1 * pow(10, maxLen) + (z3-z1-z2) * pow(10, maxLen//2) + z2
x = 171
y = 571

xy1 = karatsubaMulti(x, y)

print(xy1)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
n.y
  • 25
  • 4

1 Answers1

0

Look at the formula carefully, compare that with the correct formula, and you'll see that the square of pow(10, maxLen//2) is not pow(10, maxLen).

user202729
  • 3,358
  • 3
  • 25
  • 36