Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Karatsuba multiplication error for large integers in Python

I’ve been trying to implement the Karatsuba algorithm in Python3 in the following way:

def karatsuba(num1,num2):
    n_max = max(len(str(int(num1))), len(str(int(num2))))
    if n_max == 1:
        return int(num1*num2)

    n = n_max + n_max%2

    a = num1//10**(n/2)
    b = num1%10**(n/2)
    c = num2//10**(n/2)
    d = num2%10**(n/2)

    t1 = karatsuba(a,c)
    t3 = karatsuba(b,d)
    t2 = karatsuba(a+b,c+d) - t1 - t3

    return int(t1*10**n + t2*10**(n/2) + t3)

While the function works for small products, it fails for ones that exceed 18 digits. One can see this by running, say,

import random

for i in range(1,12):
    a = random.randint(10**i, 10**(i+1)-1)
    b = random.randint(10**i, 10**(i+1)-1)
    print(f"{len(str(a*b))} digits, error: {abs(a*b - karatsuba(a,b))}")

I would appreciate if someone could explain what is the root of this problem and, if possible, how could this code be modified to fix it. My best guess is that some round-off error is committed by Python at some point. That said, I don’t really know how int fundamentally works in this language.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use n//2 instead of n/2 to stay with ints and avoid that precision loss due to that float value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading