Python在乘法时在数字末尾添加垃圾值

时间:2017-08-19 07:07:19

标签: python python-2.7 long-integer karatsuba

我正在尝试做Karatsuba乘法。每当数字位数超过16时,python在乘以10的幂时填充垃圾值

例如:

5789640666777942 * pow(10,16)= 57896406667779421501721023610880

OR

10023051467610476 * pow(10,8)= 1002305146761047575625728

我在最后解决这个问题。我一个月以来一直在研究代码(其他部分介于两者之间)。任何帮助将不胜感激。

编辑:发布整个代码:

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]))

我想成倍增加:7878064237045606和7349065192669285

我正在使用64位计算机。而python是2.7.12。 64位。

结束问题。找到解决方案:
Karatsuba algorithm working for small numbers but not for big ones, can't see why

问题是电源功能将输出作为浮点数。内置**效果更好。

1 个答案:

答案 0 :(得分:0)

使用Decimal包,但一定要替换所有值,否则可能无效。