1

I am trying to do Karatsuba multiplication. Whenever the number of digits exceed 16, python fills garbage values at the end when multiplying by a power of 10

For example:

5789640666777942 * pow(10, 16) = 57896406667779421501721023610880

OR

10023051467610476 * pow(10, 8) = 1002305146761047575625728

I am at my wits end to solve this. I have been working on the code since a month (with other parts in between). Any help will be appreciated.

EDIT: Posting entire code:

def Karatsuba(X, Y, n):
    m = long(ceil(1.0*long(long(n)/2)))
    n = long(2*long(m))
    dem = pow(10, long(m))
    a = long(long(X)/dem)
    b = long(long(X)%dem)
    c = long(long(Y)/dem)
    d = long(long(Y)%dem)
    print "X %d Y %d" % (X, Y)
    print "a b c d n m = %d %d %d %d %d %d" %(a, b, c, d, n, m)

    if n > 2:
        print "n > 2 hence m n %d %d" % (m, n)
        p = long(Karatsuba(long(a), long(c), long(m)))
        print "p = %d" % p
        q = long(Karatsuba(long(b), long(d), long(m)))
        print "q = %d" % q
        r = long(Karatsuba(long(long(a)+long(b)), long(long(c)+long(d)), long(m)))
        print "r = %d" % r
        r = long(long(r) - long(p) - long(q))
        print "p = %d" % p
        print "q = %d" % q
        print "r = %d" % r
    else:
        print "n <= 2 hence m n %d %d" % (m, n)
        p = a*c
        print "P, A, C = %d %d %d" % (p, a, c)
        q = b*d
        print "Q, B, D = %d %d %d" % (q, b, d)
        r = (a+b) * (c+d) - p - q
        print "P = %d" % p
        print "Q = %d" % q
        print "R = %d" % r


    result = long(add(add(long(q), long(long(r) * pow(10, long(m)))), long(long(p) * pow(10, long(n)) )))
    print "result %d p %d n %d p*pow(10, n) %d r %d m %d r*pow(10, m) %d q %d" %(long(result), long(p), long(n), long(long(p)*pow(10, long(n))), long(r), long(m), long(long(r)*pow(10, long(m))), long(q))
    return str(result)


X = long(argv[1])
Y = long(argv[2])

print Karatsuba(X, Y, len(argv[1]))

I am trying to multiply:7878064237045606 and 7349065192669285

I am using 64-bit computer. And python is 2.7.12. 64-bit.

Closing the question. Found solution here:
Karatsuba algorithm working for small numbers but not for big ones, can't see why

Problem is power function gives output as float. Built in ** works better.

1 Answers1

0

Use the Decimal package, but be sure to replace all values or it may not work.

djspoulter
  • 41
  • 2
  • This answer would be improved by explaining why the Decimal package would help and a short demo on how to use it, as well as a link to the API. – SethMMorton Aug 19 '17 at 07:28
  • Very true, but difficult to achieve when answering on a small phone waiting for a bus! – djspoulter Aug 19 '17 at 07:35