我正在尝试做 Karatsuba 乘法。每当位数超过16时,python在乘以10的幂时最后填充垃圾值
例如:
5789640666777942 * pow(10, 16) = 57896406667779421501721023610880
或者
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 算法适用于小数但不适用于大数,不明白为什么
问题是幂函数将输出作为浮点数。内置**效果更好。