-2

So i'm new to python and wrote this code from a pseudocode for karatsuba multiplication and am getting an logical error of some sort

here is the pseudo code I used:

    procedure karatsuba(num1, num2)
  if (num1 < 10) or (num2 < 10)
    return num1*num2
  /* calculates the size of the numbers */
  m = max(size_base10(num1), size_base10(num2))
  m2 = m/2
  /* split the digit sequences about the middle */
  high1, low1 = split_at(num1, m2)
  high2, low2 = split_at(num2, m2)
  /* 3 calls made to numbers approximately half the size */
  z0 = karatsuba(low1,low2)
  z1 = karatsuba((low1+high1),(low2+high2))
  z2 = karatsuba(high1,high2)
  return (z2*10^(2*m2))+((z1-z2-z0)*10^(m2))+(z0)

Here is the python code for it:

def mul(n1,n2):

if n1<10 or n2<10:
    return n1*n2

l = max(len(str(n1)),len(str(n2)))
print(l)
half = l//2
print(half)

f1 = int(str(n1)[:half])
print("f1",f1)
l1 = int(str(n1)[half:])
print("l1",l1)
f2 = int(str(n2)[:half])
print("f2",f2)
l2 = int(str(n2)[half:])
print("l2",l2)

c = mul(l1,l2)
print("c",c)
b = mul((l1+f1),(l2+f2))
print("b",b)
a = mul(f1,f2)
print("a",a)

return ((a*10^(2*half))+((b-a-c)*10^(half))+c)
var = mul(44,21)
print(var)

If anyone has done this algorithm, can anyone suggest where i am getting it wrong?

Any help would be appreciated.

  • It tells you that the line with `a = mul(f1+f2)` is problematic because your need one more argument to use the function. – keepAlive Oct 12 '17 at 04:22
  • `a = mul(f1+f2)` – Shadow Oct 12 '17 at 04:22
  • Thanks a lot for the quick reply guys. – Sahil Sharma Oct 12 '17 at 04:28
  • 1
    I guess that the problem is with your exponentiation operator `^`. Use `**`. You should report your full error-trackback to maximize your chance of getting an answer. Also do not change your question as you did, post another. – keepAlive Oct 12 '17 at 05:03
  • Oh. Sorry didn’t know that, will surely do from next time. And thanks for solving the problem , It works perfectly fine now. – Sahil Sharma Oct 12 '17 at 05:12
  • 1
    @Kanak post your message as an answer to his question so you can get points for solving his problem. – TheGreatContini Oct 12 '17 at 06:03
  • You have been happy of obtaining answers on SO? Consider reading [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers). – keepAlive Oct 29 '17 at 20:29

1 Answers1

2

Your problem may come from the exponentiation operator that you use. Note that

^ is the xor operator.

while

** is used for exponentiation

>>> 2**3
8

or equivalently, you can use the built-in function pow

>>> pow(2, 3)
8
keepAlive
  • 6,369
  • 5
  • 24
  • 39