Skip to content

Commit bc9677d

Browse files
Create Karatsuba_Multiplication_Algortihm.py
1 parent b353b47 commit bc9677d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Karatsuba_Multiplication_Algortihm.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Karatsuba's algorithm
2+
# Step 1: Divide both the numbers into two halves (String wise) to form A,B,C,D
3+
# Step 2: Compute AxC and BxD (Recursive Multiplication)
4+
# Step 3: Compute (A+B)x(C+D) (Again Recursive Multiplication)
5+
# Step 4: Compute (A+B)x(C+D) - AxC - BxD
6+
# Step 5: The answer to the problem is 10^n(AxC) + 10^(n/2)(AxD+BxC)+BxD {This is a recursive approach}
7+
8+
def KMul(x, y):
9+
if len(str(x)) == 1 or len(str(y)) == 1:
10+
return x * y
11+
else:
12+
n = max(len(str(x)), len(str(y)))
13+
nby2 = n // 2
14+
a = x // 10**nby2
15+
b = x % 10**nby2
16+
c = y // 10**nby2
17+
d = y % 10**nby2
18+
ac = KMul(a, c)
19+
bd = KMul(b, d)
20+
ad_plus_bc = KMul(a + b, c + d) - ac - bd
21+
prod = ac * 10**(2 * nby2) + (ad_plus_bc * 10**nby2) + bd
22+
return prod
23+
24+
# Input
25+
x = int(input("Enter Number x: "))
26+
y = int(input("Enter Number y: "))
27+
28+
# Output
29+
result = KMul(x, y)
30+
print("Product:", result)

0 commit comments

Comments
 (0)