Having the hardest time figuring out rounding issue in my python code that is supposed to output the multiplied value of 2 numbers using Karatsuba's algorithm [ 1 , 2 ]. This is my code:
def mult(num1,num2):
if num1 < 10 or num2 < 10:
return int(num1*num2)
else:
n = len(str(num1))
a = int(str(num1)[:-(int(n/2))])
#print(a)
c = int(str(num2)[:-(int(n/2))])
#print(c)
b = int(str(num1)[-(int(n/2)):])
#print(b)
d = int(str(num2)[-(int(n/2)):])
#print(d)
val1 = mult(a,c)
val2 = mult(b,d)
val3 = mult(a+b,c+d) - val1 - val2
ans = val1*(10**int(n)) + val2 + (val3)*(10**(int(n/2)))
return int(ans)
I will add any additional info needed, please let me know Any help in this regards is much appreciated Thank you
In found a working example of the Karatsuba algorithm: https://pythonandr.com/2015/10/13/karatsuba-multiplication-algorithm-python-code/
I think your problem is that you cannot handle odd n in this way. For example multiplying 100 with 100: If you round 1.5 to 2 you get 100 000 a zero to much and if your round it to 1 your get 1000 with a zero missing. Also you should take the max number of digits from both numbers not just num1.
I hope the code below can help you solving your problem:
def karatsuba(x,y):
"""Function to multiply 2 numbers in a more efficient manner than the grade school algorithm"""
if len(str(x)) == 1 or len(str(y)) == 1:
return x*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)
ad_plus_bc = karatsuba(a+b,c+d) - ac - bd
# this little trick, writing n as 2*nby2 takes care of both even and odd n
prod = ac * 10**(2*nby2) + (ad_plus_bc * 10**nby2) + bd
return prod
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.