Skip to content

Commit 61f7f94

Browse files
rishabh0098cclauss
authored andcommitted
Create karatsuba.py (TheAlgorithms#1309)
* Create karatsuba.py Added karatsuba algorithm for multiplication of two numbers * Update karatsuba.py Added doctests and divmod * Update karatsuba.py
1 parent e80d248 commit 61f7f94

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

maths/karatsuba.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
True
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

Comments
 (0)