28280
2929"""
3030
31-
32- def karatsuba_multiply (x : str , y : str ) -> int :
31+ def karatsuba_multiply (binary_str_1 : str , binary_str_2 : str ) -> int :
3332 """
3433 Multiplies two binary strings using the Karatsuba algorithm.
3534
@@ -42,37 +41,38 @@ def karatsuba_multiply(x: str, y: str) -> int:
4241 >>> karatsuba_multiply("1111", "1111")
4342 225
4443 """
45- n = max (len (x ), len (y ))
44+ n = max (len (binary_str_1 ), len (binary_str_2 ))
4645
4746 # Pad the shorter string with leading zeros
48- x = x .zfill (n )
49- y = y .zfill (n )
47+ binary_str_1 = binary_str_1 .zfill (n )
48+ binary_str_2 = binary_str_2 .zfill (n )
5049
5150 # Base case: single bit multiplication
5251 if n == 1 :
53- return int (x ) * int (y )
52+ return int (binary_str_1 ) * int (binary_str_2 )
5453
5554 mid = n // 2
5655
5756 # Split the binary strings into left and right halves
58- x_left , x_right = x [:mid ], x [mid :]
59- y_left , y_right = y [:mid ], y [mid :]
57+ left_1 , right_1 = binary_str_1 [:mid ], binary_str_1 [mid :]
58+ left_2 , right_2 = binary_str_2 [:mid ], binary_str_2 [mid :]
6059
6160 # Recursively compute partial products
62- p1 = karatsuba_multiply (x_left , y_left )
63- p2 = karatsuba_multiply (x_right , y_right )
64- p3 = karatsuba_multiply (
65- bin (int (x_left , 2 ) + int (x_right , 2 ))[2 :],
66- bin (int (y_left , 2 ) + int (y_right , 2 ))[2 :],
61+ product_left = karatsuba_multiply (left_1 , left_2 )
62+ product_right = karatsuba_multiply (right_1 , right_2 )
63+ product_sum = karatsuba_multiply (
64+ bin (int (left_1 , 2 ) + int (right_1 , 2 ))[2 :],
65+ bin (int (left_2 , 2 ) + int (right_2 , 2 ))[2 :]
6766 )
6867
69- # Karatsuba combination formula:
70- result = (p1 << (2 * (n - mid ))) + ((p3 - p1 - p2 ) << (n - mid )) + p2
68+ # Karatsuba combination formula
69+ result = (product_left << (2 * (n - mid ))) + (
70+ (product_sum - product_left - product_right ) << (n - mid )
71+ ) + product_right
7172
7273 return result
7374
7475
7576if __name__ == "__main__" :
7677 import doctest
77-
7878 doctest .testmod ()
0 commit comments