Skip to content

Commit bbbbbcd

Browse files
authored
Merge pull request ephremdeme#209 from STK101/master
Create karatsuba_algorithm.py
2 parents ce1d44f + f061431 commit bbbbbcd

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-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

Mathematics/LCM/LCM.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
public class Main {
2+
public static void main(String[] args) {
3+
4+
int n1 = 72, n2 = 120, lcm;
5+
6+
// maximum number between n1 and n2 is stored in lcm
7+
lcm = (n1 > n2) ? n1 : n2;
8+
9+
// Always true
10+
while(true) {
11+
if( lcm % n1 == 0 && lcm % n2 == 0 ) {
12+
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
13+
break;
14+
}
15+
++lcm;
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)