Skip to content

Commit 14aa9a9

Browse files
authored
Create karatsuba_algorithm.py
The Karatsuba algorithm is a fast multiplication algorithm.It reduces the multiplication of two n-digit numbers to at most n^log2(3).
1 parent b947cb9 commit 14aa9a9

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Algorithms/karatsuba_algorithm.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def zero(numberString, zeros, left = True):
2+
"""Return the string with zeros added to the left or right."""
3+
for i in range(zeros):
4+
if left:
5+
numberString = '0' + numberString
6+
else:
7+
numberString = numberString + '0'
8+
return numberString
9+
10+
11+
def Multiplication(x ,y):
12+
13+
x = str(x)
14+
y = str(y)
15+
# recursion base case
16+
if len(x) == 1 and len(y) == 1:
17+
return int(x) * int(y)
18+
if len(x) < len(y):
19+
x = zero(x, len(y) - len(x))
20+
elif len(y) < len(x):
21+
y = zero(y, len(x) - len(y))
22+
n = len(x)
23+
j = n//2
24+
if (n % 2) != 0:
25+
j += 1
26+
BZeroPadding = n - j
27+
AZeroPadding = BZeroPadding * 2
28+
a = int(x[:j])
29+
b = int(x[j:])
30+
c = int(y[:j])
31+
d = int(y[j:])
32+
ac = Multiplication(a, c)
33+
bd = Multiplication(b, d)
34+
k = Multiplication(a + b, c + d)
35+
A = int(zero(str(ac), AZeroPadding, False))
36+
B = int(zero(str(k - ac - bd), BZeroPadding, False))
37+
return A + B + bd

0 commit comments

Comments
 (0)