We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 4ac5b9b + ceefd98 commit f85ef4bCopy full SHA for f85ef4b
sorting and basics/karatsuba.py
@@ -6,17 +6,17 @@ def karatsuba(x, y, b=10):
6
>>> karatsuba(1234223123412323, 1234534213423333123)
7
1523690672850721578619752112274729L
8
"""
9
- nx, ny = len(str(x))/2, len(str(y))/2
10
- if x < 1000 or y < 1000: return x * y
11
- m = nx if nx < ny else ny
12
- x1 = x / (b**m)
13
- x0 = x % (x1 * (b**m))
14
- y1 = y / (b**m)
15
- y0 = y % (y1 * (b**m))
16
- z1 = karatsuba(x1,y1,b)
17
- z3 = karatsuba(x0,y0,b)
+
+ if x < 1000 or y < 1000:
+ return x * y
+ m = min(len(str(x)) / 2, len(str(y)) / 2)
+ bm = b**m
+ x1, x0 = x / bm, x % bm
+ y1, y0 = y / bm, y % bm
+ z1 = karatsuba(x1, y1, b)
+ z3 = karatsuba(x0, y0, b)
18
z2 = karatsuba(x1 + x0, y1 + y0, b) - z1 - z3
19
- return (b**(2*m))*z1 + (b**m)*z2 + z3
+ return (bm**2)*z1 + bm*z2 + z3
20
21
if __name__ == "__main__":
22
import doctest
0 commit comments