We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e80d248 commit 61f7f94Copy full SHA for 61f7f94
maths/karatsuba.py
@@ -0,0 +1,31 @@
1
+""" Multiply two numbers using Karatsuba algorithm """
2
+
3
+def karatsuba(a, b):
4
+ """
5
+ >>> karatsuba(15463, 23489) == 15463 * 23489
6
+ True
7
+ >>> karatsuba(3, 9) == 3 * 9
8
9
10
+ if len(str(a)) == 1 or len(str(b)) == 1:
11
+ return (a * b)
12
+ else:
13
+ m1 = max(len(str(a)), len(str(b)))
14
+ m2 = m1 // 2
15
16
+ a1, a2 = divmod(a, 10**m2)
17
+ b1, b2 = divmod(b, 10**m2)
18
19
+ x = karatsuba(a2, b2)
20
+ y = karatsuba((a1 + a2), (b1 + b2))
21
+ z = karatsuba(a1, b1)
22
23
+ return ((z * 10**(2*m2)) + ((y - z - x) * 10**(m2)) + (x))
24
25
26
+def main():
27
+ print(karatsuba(15463, 23489))
28
29
30
+if __name__ == "__main__":
31
+ main()
0 commit comments